encoder_example.c 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890
  1. /********************************************************************
  2. * *
  3. * THIS FILE IS PART OF THE OggTheora SOFTWARE CODEC SOURCE CODE. *
  4. * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
  5. * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
  6. * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
  7. * *
  8. * THE Theora SOURCE CODE IS COPYRIGHT (C) 2002-2009 *
  9. * by the Xiph.Org Foundation and contributors http://www.xiph.org/ *
  10. * *
  11. ********************************************************************
  12. function: example encoder application; makes an Ogg Theora/Vorbis
  13. file from YUV4MPEG2 and WAV input
  14. last mod: $Id$
  15. ********************************************************************/
  16. #if !defined(_REENTRANT)
  17. #define _REENTRANT
  18. #endif
  19. #if !defined(_GNU_SOURCE)
  20. #define _GNU_SOURCE
  21. #endif
  22. #if !defined(_LARGEFILE_SOURCE)
  23. #define _LARGEFILE_SOURCE
  24. #endif
  25. #if !defined(_LARGEFILE64_SOURCE)
  26. #define _LARGEFILE64_SOURCE
  27. #endif
  28. #if !defined(_FILE_OFFSET_BITS)
  29. #define _FILE_OFFSET_BITS 64
  30. #endif
  31. /*#define OC_COLLECT_METRICS*/
  32. #include <stdio.h>
  33. #if !defined(_WIN32)
  34. #include <getopt.h>
  35. #include <unistd.h>
  36. #else
  37. #include "getopt.h"
  38. #endif
  39. #include <stdlib.h>
  40. #include <string.h>
  41. #include <time.h>
  42. #include <math.h>
  43. #include "theora/theoraenc.h"
  44. #include "vorbis/codec.h"
  45. #include "vorbis/vorbisenc.h"
  46. #ifdef _WIN32
  47. /*supply missing headers and functions to Win32. going to hell, I know*/
  48. #include <fcntl.h>
  49. #include <io.h>
  50. static double rint(double x)
  51. {
  52. if (x < 0.0)
  53. return (double)(int)(x - 0.5);
  54. else
  55. return (double)(int)(x + 0.5);
  56. }
  57. #endif
  58. #if defined(OC_COLLECT_METRICS)
  59. # define TH_ENCCTL_SET_METRICS_FILE (0x8000)
  60. #endif
  61. const char *optstring = "b:e:o:a:A:v:V:s:S:f:F:qck:d:z:\1\2\3\4"
  62. #if defined(OC_COLLECT_METRICS)
  63. "m:"
  64. #endif
  65. ;
  66. struct option options [] = {
  67. {"begin-time",required_argument,NULL,'b'},
  68. {"end-time",required_argument,NULL,'e'},
  69. {"output",required_argument,NULL,'o'},
  70. {"audio-rate-target",required_argument,NULL,'A'},
  71. {"video-rate-target",required_argument,NULL,'V'},
  72. {"audio-quality",required_argument,NULL,'a'},
  73. {"video-quality",required_argument,NULL,'v'},
  74. {"aspect-numerator",required_argument,NULL,'s'},
  75. {"aspect-denominator",required_argument,NULL,'S'},
  76. {"framerate-numerator",required_argument,NULL,'f'},
  77. {"framerate-denominator",required_argument,NULL,'F'},
  78. {"quiet",no_argument,NULL,'q'},
  79. {"vp3-compatible",no_argument,NULL,'c'},
  80. {"speed",required_argument,NULL,'z'},
  81. {"soft-target",no_argument,NULL,'\1'},
  82. {"keyframe-freq",required_argument,NULL,'k'},
  83. {"buf-delay",required_argument,NULL,'d'},
  84. {"two-pass",no_argument,NULL,'\2'},
  85. {"first-pass",required_argument,NULL,'\3'},
  86. {"second-pass",required_argument,NULL,'\4'},
  87. #if defined(OC_COLLECT_METRICS)
  88. {"metrics-file",required_argument,NULL,'m'},
  89. #endif
  90. {NULL,0,NULL,0}
  91. };
  92. /* You'll go to Hell for using globals. */
  93. FILE *audio=NULL;
  94. FILE *video=NULL;
  95. int audio_ch=0;
  96. int audio_hz=0;
  97. float audio_q=.1f;
  98. int audio_r=-1;
  99. int vp3_compatible=0;
  100. int quiet=0;
  101. int frame_w=0;
  102. int frame_h=0;
  103. int pic_w=0;
  104. int pic_h=0;
  105. int pic_x=0;
  106. int pic_y=0;
  107. int video_fps_n=-1;
  108. int video_fps_d=-1;
  109. int video_par_n=-1;
  110. int video_par_d=-1;
  111. char interlace;
  112. int src_c_dec_h=2;
  113. int src_c_dec_v=2;
  114. int dst_c_dec_h=2;
  115. int dst_c_dec_v=2;
  116. char chroma_type[16];
  117. /*The size of each converted frame buffer.*/
  118. size_t y4m_dst_buf_sz;
  119. /*The amount to read directly into the converted frame buffer.*/
  120. size_t y4m_dst_buf_read_sz;
  121. /*The size of the auxilliary buffer.*/
  122. size_t y4m_aux_buf_sz;
  123. /*The amount to read into the auxilliary buffer.*/
  124. size_t y4m_aux_buf_read_sz;
  125. /*The function used to perform chroma conversion.*/
  126. typedef void (*y4m_convert_func)(unsigned char *_dst,unsigned char *_aux);
  127. y4m_convert_func y4m_convert=NULL;
  128. int video_r=-1;
  129. int video_q=-1;
  130. ogg_uint32_t keyframe_frequency=0;
  131. int buf_delay=-1;
  132. long begin_sec=-1;
  133. long begin_usec=0;
  134. long end_sec=-1;
  135. long end_usec=0;
  136. static void usage(void){
  137. fprintf(stderr,
  138. "Usage: encoder_example [options] [audio_file] video_file\n\n"
  139. "Options: \n\n"
  140. " -o --output <filename.ogv> file name for encoded output;\n"
  141. " If this option is not given, the\n"
  142. " compressed data is sent to stdout.\n\n"
  143. " -A --audio-rate-target <n> bitrate target for Vorbis audio;\n"
  144. " use -a and not -A if at all possible,\n"
  145. " as -a gives higher quality for a given\n"
  146. " bitrate.\n\n"
  147. " -V --video-rate-target <n> bitrate target for Theora video\n\n"
  148. " --soft-target Use a large reservoir and treat the rate\n"
  149. " as a soft target; rate control is less\n"
  150. " strict but resulting quality is usually\n"
  151. " higher/smoother overall. Soft target also\n"
  152. " allows an optional -v setting to specify\n"
  153. " a minimum allowed quality.\n\n"
  154. " --two-pass Compress input using two-pass rate control\n"
  155. " This option requires that the input to the\n"
  156. " to the encoder is seekable and performs\n"
  157. " both passes automatically.\n\n"
  158. " --first-pass <filename> Perform first-pass of a two-pass rate\n"
  159. " controlled encoding, saving pass data to\n"
  160. " <filename> for a later second pass\n\n"
  161. " --second-pass <filename> Perform second-pass of a two-pass rate\n"
  162. " controlled encoding, reading first-pass\n"
  163. " data from <filename>. The first pass\n"
  164. " data must come from a first encoding pass\n"
  165. " using identical input video to work\n"
  166. " properly.\n\n"
  167. " -a --audio-quality <n> Vorbis quality selector from -1 to 10\n"
  168. " (-1 yields smallest files but lowest\n"
  169. " fidelity; 10 yields highest fidelity\n"
  170. " but large files. '2' is a reasonable\n"
  171. " default).\n\n"
  172. " -v --video-quality <n> Theora quality selector from 0 to 10\n"
  173. " (0 yields smallest files but lowest\n"
  174. " video quality. 10 yields highest\n"
  175. " fidelity but large files).\n\n"
  176. " -s --aspect-numerator <n> Aspect ratio numerator, default is 0\n"
  177. " or extracted from YUV input file\n"
  178. " -S --aspect-denominator <n> Aspect ratio denominator, default is 0\n"
  179. " or extracted from YUV input file\n"
  180. " -f --framerate-numerator <n> Frame rate numerator, can be extracted\n"
  181. " from YUV input file. ex: 30000000\n"
  182. " -F --framerate-denominator <n> Frame rate denominator, can be extracted\n"
  183. " from YUV input file. ex: 1000000\n"
  184. " The frame rate nominator divided by this\n"
  185. " determinates the frame rate in units per tick\n"
  186. " -k --keyframe-freq <n> Keyframe frequency\n"
  187. " -z --speed <n> Sets the encoder speed level. Higher speed\n"
  188. " levels favor quicker encoding over better\n"
  189. " quality per bit. Depending on the encoding\n"
  190. " mode, and the internal algorithms used,\n"
  191. " quality may actually improve with higher\n"
  192. " speeds, but in this case bitrate will also\n"
  193. " likely increase. The maximum value, and the\n"
  194. " meaning of each value, are implementation-\n"
  195. " specific and may change depending on the\n"
  196. " current encoding mode (rate constrained,\n"
  197. " two-pass, etc.).\n"
  198. " -d --buf-delay <n> Buffer delay (in frames). Longer delays\n"
  199. " allow smoother rate adaptation and provide\n"
  200. " better overall quality, but require more\n"
  201. " client side buffering and add latency. The\n"
  202. " default value is the keyframe interval for\n"
  203. " one-pass encoding (or somewhat larger if\n"
  204. " --soft-target is used) and infinite for\n"
  205. " two-pass encoding.\n"
  206. " -b --begin-time <h:m:s.d> Begin encoding at offset into input\n"
  207. " -e --end-time <h:m:s.d> End encoding at offset into input\n\n"
  208. " -q --quiet Don't print progress information.\n\n"
  209. #if defined(OC_COLLECT_METRICS)
  210. " -m --metrics-filename File in which to accumulate mode decision\n"
  211. " metrics. Statistics from the current\n"
  212. " encode will be merged with those already\n"
  213. " in the file if it exists.\n\n"
  214. #endif
  215. "encoder_example accepts only uncompressed RIFF WAV format audio and\n"
  216. "YUV4MPEG2 uncompressed video.\n\n");
  217. exit(1);
  218. }
  219. static int y4m_parse_tags(char *_tags){
  220. int got_w;
  221. int got_h;
  222. int got_fps;
  223. int got_interlace;
  224. int got_par;
  225. int got_chroma;
  226. int tmp_video_fps_n;
  227. int tmp_video_fps_d;
  228. int tmp_video_par_n;
  229. int tmp_video_par_d;
  230. char *p;
  231. char *q;
  232. got_w=got_h=got_fps=got_interlace=got_par=got_chroma=0;
  233. for(p=_tags;;p=q){
  234. /*Skip any leading spaces.*/
  235. while(*p==' ')p++;
  236. /*If that's all we have, stop.*/
  237. if(p[0]=='\0')break;
  238. /*Find the end of this tag.*/
  239. for(q=p+1;*q!='\0'&&*q!=' ';q++);
  240. /*Process the tag.*/
  241. switch(p[0]){
  242. case 'W':{
  243. if(sscanf(p+1,"%d",&pic_w)!=1)return -1;
  244. got_w=1;
  245. }break;
  246. case 'H':{
  247. if(sscanf(p+1,"%d",&pic_h)!=1)return -1;
  248. got_h=1;
  249. }break;
  250. case 'F':{
  251. if(sscanf(p+1,"%d:%d",&tmp_video_fps_n,&tmp_video_fps_d)!=2)return -1;
  252. got_fps=1;
  253. }break;
  254. case 'I':{
  255. interlace=p[1];
  256. got_interlace=1;
  257. }break;
  258. case 'A':{
  259. if(sscanf(p+1,"%d:%d",&tmp_video_par_n,&tmp_video_par_d)!=2)return -1;
  260. got_par=1;
  261. }break;
  262. case 'C':{
  263. if(q-p>16)return -1;
  264. memcpy(chroma_type,p+1,q-p-1);
  265. chroma_type[q-p-1]='\0';
  266. got_chroma=1;
  267. }break;
  268. /*Ignore unknown tags.*/
  269. }
  270. }
  271. if(!got_w||!got_h||!got_fps||!got_interlace||!got_par)return -1;
  272. /*Chroma-type is not specified in older files, e.g., those generated by
  273. mplayer.*/
  274. if(!got_chroma)strcpy(chroma_type,"420");
  275. /*Update fps and aspect ratio globals if not specified in the command line.*/
  276. if(video_fps_n==-1)video_fps_n=tmp_video_fps_n;
  277. if(video_fps_d==-1)video_fps_d=tmp_video_fps_d;
  278. if(video_par_n==-1)video_par_n=tmp_video_par_n;
  279. if(video_par_d==-1)video_par_d=tmp_video_par_d;
  280. return 0;
  281. }
  282. /*All anti-aliasing filters in the following conversion functions are based on
  283. one of two window functions:
  284. The 6-tap Lanczos window (for down-sampling and shifts):
  285. sinc(\pi*t)*sinc(\pi*t/3), |t|<3 (sinc(t)==sin(t)/t)
  286. 0, |t|>=3
  287. The 4-tap Mitchell window (for up-sampling):
  288. 7|t|^3-12|t|^2+16/3, |t|<1
  289. -(7/3)|x|^3+12|x|^2-20|x|+32/3, |t|<2
  290. 0, |t|>=2
  291. The number of taps is intentionally kept small to reduce computational
  292. overhead and limit ringing.
  293. The taps from these filters are scaled so that their sum is 1, and the result
  294. is scaled by 128 and rounded to integers to create a filter whose
  295. intermediate values fit inside 16 bits.
  296. Coefficients are rounded in such a way as to ensure their sum is still 128,
  297. which is usually equivalent to normal rounding.*/
  298. #define OC_MINI(_a,_b) ((_a)>(_b)?(_b):(_a))
  299. #define OC_MAXI(_a,_b) ((_a)<(_b)?(_b):(_a))
  300. #define OC_CLAMPI(_a,_b,_c) (OC_MAXI(_a,OC_MINI(_b,_c)))
  301. /*420jpeg chroma samples are sited like:
  302. Y-------Y-------Y-------Y-------
  303. | | | |
  304. | BR | | BR |
  305. | | | |
  306. Y-------Y-------Y-------Y-------
  307. | | | |
  308. | | | |
  309. | | | |
  310. Y-------Y-------Y-------Y-------
  311. | | | |
  312. | BR | | BR |
  313. | | | |
  314. Y-------Y-------Y-------Y-------
  315. | | | |
  316. | | | |
  317. | | | |
  318. 420mpeg2 chroma samples are sited like:
  319. Y-------Y-------Y-------Y-------
  320. | | | |
  321. BR | BR |
  322. | | | |
  323. Y-------Y-------Y-------Y-------
  324. | | | |
  325. | | | |
  326. | | | |
  327. Y-------Y-------Y-------Y-------
  328. | | | |
  329. BR | BR |
  330. | | | |
  331. Y-------Y-------Y-------Y-------
  332. | | | |
  333. | | | |
  334. | | | |
  335. We use a resampling filter to shift the site locations one quarter pixel (at
  336. the chroma plane's resolution) to the right.
  337. The 4:2:2 modes look exactly the same, except there are twice as many chroma
  338. lines, and they are vertically co-sited with the luma samples in both the
  339. mpeg2 and jpeg cases (thus requiring no vertical resampling).*/
  340. static void y4m_convert_42xmpeg2_42xjpeg(unsigned char *_dst,
  341. unsigned char *_aux){
  342. int c_w;
  343. int c_h;
  344. int pli;
  345. int y;
  346. int x;
  347. /*Skip past the luma data.*/
  348. _dst+=pic_w*pic_h;
  349. /*Compute the size of each chroma plane.*/
  350. c_w=(pic_w+dst_c_dec_h-1)/dst_c_dec_h;
  351. c_h=(pic_h+dst_c_dec_v-1)/dst_c_dec_v;
  352. for(pli=1;pli<3;pli++){
  353. for(y=0;y<c_h;y++){
  354. /*Filter: [4 -17 114 35 -9 1]/128, derived from a 6-tap Lanczos
  355. window.*/
  356. for(x=0;x<OC_MINI(c_w,2);x++){
  357. _dst[x]=(unsigned char)OC_CLAMPI(0,4*_aux[0]-17*_aux[OC_MAXI(x-1,0)]+
  358. 114*_aux[x]+35*_aux[OC_MINI(x+1,c_w-1)]-9*_aux[OC_MINI(x+2,c_w-1)]+
  359. _aux[OC_MINI(x+3,c_w-1)]+64>>7,255);
  360. }
  361. for(;x<c_w-3;x++){
  362. _dst[x]=(unsigned char)OC_CLAMPI(0,4*_aux[x-2]-17*_aux[x-1]+
  363. 114*_aux[x]+35*_aux[x+1]-9*_aux[x+2]+_aux[x+3]+64>>7,255);
  364. }
  365. for(;x<c_w;x++){
  366. _dst[x]=(unsigned char)OC_CLAMPI(0,4*_aux[x-2]-17*_aux[x-1]+
  367. 114*_aux[x]+35*_aux[OC_MINI(x+1,c_w-1)]-9*_aux[OC_MINI(x+2,c_w-1)]+
  368. _aux[c_w-1]+64>>7,255);
  369. }
  370. _dst+=c_w;
  371. _aux+=c_w;
  372. }
  373. }
  374. }
  375. /*This format is only used for interlaced content, but is included for
  376. completeness.
  377. 420jpeg chroma samples are sited like:
  378. Y-------Y-------Y-------Y-------
  379. | | | |
  380. | BR | | BR |
  381. | | | |
  382. Y-------Y-------Y-------Y-------
  383. | | | |
  384. | | | |
  385. | | | |
  386. Y-------Y-------Y-------Y-------
  387. | | | |
  388. | BR | | BR |
  389. | | | |
  390. Y-------Y-------Y-------Y-------
  391. | | | |
  392. | | | |
  393. | | | |
  394. 420paldv chroma samples are sited like:
  395. YR------Y-------YR------Y-------
  396. | | | |
  397. | | | |
  398. | | | |
  399. YB------Y-------YB------Y-------
  400. | | | |
  401. | | | |
  402. | | | |
  403. YR------Y-------YR------Y-------
  404. | | | |
  405. | | | |
  406. | | | |
  407. YB------Y-------YB------Y-------
  408. | | | |
  409. | | | |
  410. | | | |
  411. We use a resampling filter to shift the site locations one quarter pixel (at
  412. the chroma plane's resolution) to the right.
  413. Then we use another filter to move the C_r location down one quarter pixel,
  414. and the C_b location up one quarter pixel.*/
  415. static void y4m_convert_42xpaldv_42xjpeg(unsigned char *_dst,
  416. unsigned char *_aux){
  417. unsigned char *tmp;
  418. int c_w;
  419. int c_h;
  420. int c_sz;
  421. int pli;
  422. int y;
  423. int x;
  424. /*Skip past the luma data.*/
  425. _dst+=pic_w*pic_h;
  426. /*Compute the size of each chroma plane.*/
  427. c_w=(pic_w+1)/2;
  428. c_h=(pic_h+dst_c_dec_h-1)/dst_c_dec_h;
  429. c_sz=c_w*c_h;
  430. /*First do the horizontal re-sampling.
  431. This is the same as the mpeg2 case, except that after the horizontal case,
  432. we need to apply a second vertical filter.*/
  433. tmp=_aux+2*c_sz;
  434. for(pli=1;pli<3;pli++){
  435. for(y=0;y<c_h;y++){
  436. /*Filter: [4 -17 114 35 -9 1]/128, derived from a 6-tap Lanczos
  437. window.*/
  438. for(x=0;x<OC_MINI(c_w,2);x++){
  439. tmp[x]=(unsigned char)OC_CLAMPI(0,4*_aux[0]-17*_aux[OC_MAXI(x-1,0)]+
  440. 114*_aux[x]+35*_aux[OC_MINI(x+1,c_w-1)]-9*_aux[OC_MINI(x+2,c_w-1)]+
  441. _aux[OC_MINI(x+3,c_w-1)]+64>>7,255);
  442. }
  443. for(;x<c_w-3;x++){
  444. tmp[x]=(unsigned char)OC_CLAMPI(0,4*_aux[x-2]-17*_aux[x-1]+
  445. 114*_aux[x]+35*_aux[x+1]-9*_aux[x+2]+_aux[x+3]+64>>7,255);
  446. }
  447. for(;x<c_w;x++){
  448. tmp[x]=(unsigned char)OC_CLAMPI(0,4*_aux[x-2]-17*_aux[x-1]+
  449. 114*_aux[x]+35*_aux[OC_MINI(x+1,c_w-1)]-9*_aux[OC_MINI(x+2,c_w-1)]+
  450. _aux[c_w-1]+64>>7,255);
  451. }
  452. tmp+=c_w;
  453. _aux+=c_w;
  454. }
  455. switch(pli){
  456. case 1:{
  457. tmp-=c_sz;
  458. /*Slide C_b up a quarter-pel.
  459. This is the same filter used above, but in the other order.*/
  460. for(x=0;x<c_w;x++){
  461. for(y=0;y<OC_MINI(c_h,3);y++){
  462. _dst[y*c_w]=(unsigned char)OC_CLAMPI(0,tmp[0]-
  463. 9*tmp[OC_MAXI(y-2,0)*c_w]+35*tmp[OC_MAXI(y-1,0)*c_w]+
  464. 114*tmp[y*c_w]-17*tmp[OC_MINI(y+1,c_h-1)*c_w]+
  465. 4*tmp[OC_MINI(y+2,c_h-1)*c_w]+64>>7,255);
  466. }
  467. for(;y<c_h-2;y++){
  468. _dst[y*c_w]=(unsigned char)OC_CLAMPI(0,tmp[(y-3)*c_w]-
  469. 9*tmp[(y-2)*c_w]+35*tmp[(y-1)*c_w]+114*tmp[y*c_w]-
  470. 17*tmp[(y+1)*c_w]+4*tmp[(y+2)*c_w]+64>>7,255);
  471. }
  472. for(;y<c_h;y++){
  473. _dst[y*c_w]=(unsigned char)OC_CLAMPI(0,tmp[(y-3)*c_w]-
  474. 9*tmp[(y-2)*c_w]+35*tmp[(y-1)*c_w]+114*tmp[y*c_w]-
  475. 17*tmp[OC_MINI(y+1,c_h-1)*c_w]+4*tmp[(c_h-1)*c_w]+64>>7,255);
  476. }
  477. _dst++;
  478. tmp++;
  479. }
  480. _dst+=c_sz-c_w;
  481. tmp-=c_w;
  482. }break;
  483. case 2:{
  484. tmp-=c_sz;
  485. /*Slide C_r down a quarter-pel.
  486. This is the same as the horizontal filter.*/
  487. for(x=0;x<c_w;x++){
  488. for(y=0;y<OC_MINI(c_h,2);y++){
  489. _dst[y*c_w]=(unsigned char)OC_CLAMPI(0,4*tmp[0]-
  490. 17*tmp[OC_MAXI(y-1,0)*c_w]+114*tmp[y*c_w]+
  491. 35*tmp[OC_MINI(y+1,c_h-1)*c_w]-9*tmp[OC_MINI(y+2,c_h-1)*c_w]+
  492. tmp[OC_MINI(y+3,c_h-1)*c_w]+64>>7,255);
  493. }
  494. for(;y<c_h-3;y++){
  495. _dst[y*c_w]=(unsigned char)OC_CLAMPI(0,4*tmp[(y-2)*c_w]-
  496. 17*tmp[(y-1)*c_w]+114*tmp[y*c_w]+35*tmp[(y+1)*c_w]-
  497. 9*tmp[(y+2)*c_w]+tmp[(y+3)*c_w]+64>>7,255);
  498. }
  499. for(;y<c_h;y++){
  500. _dst[y*c_w]=(unsigned char)OC_CLAMPI(0,4*tmp[(y-2)*c_w]-
  501. 17*tmp[(y-1)*c_w]+114*tmp[y*c_w]+35*tmp[OC_MINI(y+1,c_h-1)*c_w]-
  502. 9*tmp[OC_MINI(y+2,c_h-1)*c_w]+tmp[(c_h-1)*c_w]+64>>7,255);
  503. }
  504. _dst++;
  505. tmp++;
  506. }
  507. }break;
  508. }
  509. /*For actual interlaced material, this would have to be done separately on
  510. each field, and the shift amounts would be different.
  511. C_r moves down 1/8, C_b up 3/8 in the top field, and C_r moves down 3/8,
  512. C_b up 1/8 in the bottom field.
  513. The corresponding filters would be:
  514. Down 1/8 (reverse order for up): [3 -11 125 15 -4 0]/128
  515. Down 3/8 (reverse order for up): [4 -19 98 56 -13 2]/128*/
  516. }
  517. }
  518. /*422jpeg chroma samples are sited like:
  519. Y---BR--Y-------Y---BR--Y-------
  520. | | | |
  521. | | | |
  522. | | | |
  523. Y---BR--Y-------Y---BR--Y-------
  524. | | | |
  525. | | | |
  526. | | | |
  527. Y---BR--Y-------Y---BR--Y-------
  528. | | | |
  529. | | | |
  530. | | | |
  531. Y---BR--Y-------Y---BR--Y-------
  532. | | | |
  533. | | | |
  534. | | | |
  535. 411 chroma samples are sited like:
  536. YBR-----Y-------Y-------Y-------
  537. | | | |
  538. | | | |
  539. | | | |
  540. YBR-----Y-------Y-------Y-------
  541. | | | |
  542. | | | |
  543. | | | |
  544. YBR-----Y-------Y-------Y-------
  545. | | | |
  546. | | | |
  547. | | | |
  548. YBR-----Y-------Y-------Y-------
  549. | | | |
  550. | | | |
  551. | | | |
  552. We use a filter to resample at site locations one eighth pixel (at the source
  553. chroma plane's horizontal resolution) and five eighths of a pixel to the
  554. right.*/
  555. static void y4m_convert_411_422jpeg(unsigned char *_dst,
  556. unsigned char *_aux){
  557. int c_w;
  558. int dst_c_w;
  559. int c_h;
  560. int pli;
  561. int y;
  562. int x;
  563. /*Skip past the luma data.*/
  564. _dst+=pic_w*pic_h;
  565. /*Compute the size of each chroma plane.*/
  566. c_w=(pic_w+src_c_dec_h-1)/src_c_dec_h;
  567. dst_c_w=(pic_w+dst_c_dec_h-1)/dst_c_dec_h;
  568. c_h=(pic_h+dst_c_dec_v-1)/dst_c_dec_v;
  569. for(pli=1;pli<3;pli++){
  570. for(y=0;y<c_h;y++){
  571. /*Filters: [1 110 18 -1]/128 and [-3 50 86 -5]/128, both derived from a
  572. 4-tap Mitchell window.*/
  573. for(x=0;x<OC_MINI(c_w,1);x++){
  574. _dst[x<<1]=(unsigned char)OC_CLAMPI(0,111*_aux[0]+
  575. 18*_aux[OC_MINI(1,c_w-1)]-_aux[OC_MINI(2,c_w-1)]+64>>7,255);
  576. _dst[x<<1|1]=(unsigned char)OC_CLAMPI(0,47*_aux[0]+
  577. 86*_aux[OC_MINI(1,c_w-1)]-5*_aux[OC_MINI(2,c_w-1)]+64>>7,255);
  578. }
  579. for(;x<c_w-2;x++){
  580. _dst[x<<1]=(unsigned char)OC_CLAMPI(0,_aux[x-1]+110*_aux[x]+
  581. 18*_aux[x+1]-_aux[x+2]+64>>7,255);
  582. _dst[x<<1|1]=(unsigned char)OC_CLAMPI(0,-3*_aux[x-1]+50*_aux[x]+
  583. 86*_aux[x+1]-5*_aux[x+2]+64>>7,255);
  584. }
  585. for(;x<c_w;x++){
  586. _dst[x<<1]=(unsigned char)OC_CLAMPI(0,_aux[x-1]+110*_aux[x]+
  587. 18*_aux[OC_MINI(x+1,c_w-1)]-_aux[c_w-1]+64>>7,255);
  588. if((x<<1|1)<dst_c_w){
  589. _dst[x<<1|1]=(unsigned char)OC_CLAMPI(0,-3*_aux[x-1]+50*_aux[x]+
  590. 86*_aux[OC_MINI(x+1,c_w-1)]-5*_aux[c_w-1]+64>>7,255);
  591. }
  592. }
  593. _dst+=dst_c_w;
  594. _aux+=c_w;
  595. }
  596. }
  597. }
  598. /*The image is padded with empty chroma components at 4:2:0.
  599. This costs about 17 bits a frame to code.*/
  600. static void y4m_convert_mono_420jpeg(unsigned char *_dst,
  601. unsigned char *_aux){
  602. int c_sz;
  603. _dst+=pic_w*pic_h;
  604. c_sz=((pic_w+dst_c_dec_h-1)/dst_c_dec_h)*((pic_h+dst_c_dec_v-1)/dst_c_dec_v);
  605. memset(_dst,128,c_sz*2);
  606. }
  607. #if 0
  608. /*Right now just 444 to 420.
  609. Not too hard to generalize.*/
  610. static void y4m_convert_4xxjpeg_42xjpeg(unsigned char *_dst,
  611. unsigned char *_aux){
  612. unsigned char *tmp;
  613. int c_w;
  614. int c_h;
  615. int pic_sz;
  616. int tmp_sz;
  617. int c_sz;
  618. int pli;
  619. int y;
  620. int x;
  621. /*Compute the size of each chroma plane.*/
  622. c_w=(pic_w+dst_c_dec_h-1)/dst_c_dec_h;
  623. c_h=(pic_h+dst_c_dec_v-1)/dst_c_dec_v;
  624. pic_sz=pic_w*pic_h;
  625. tmp_sz=c_w*pic_h;
  626. c_sz=c_w*c_h;
  627. _dst+=pic_sz;
  628. for(pli=1;pli<3;pli++){
  629. tmp=_aux+pic_sz;
  630. /*In reality, the horizontal and vertical steps could be pipelined, for
  631. less memory consumption and better cache performance, but we do them
  632. separately for simplicity.*/
  633. /*First do horizontal filtering (convert to 4:2:2)*/
  634. /*Filter: [3 -17 78 78 -17 3]/128, derived from a 6-tap Lanczos window.*/
  635. for(y=0;y<pic_h;y++){
  636. for(x=0;x<OC_MINI(pic_w,2);x+=2){
  637. tmp[x>>1]=OC_CLAMPI(0,64*_aux[0]+78*_aux[OC_MINI(1,pic_w-1)]-
  638. 17*_aux[OC_MINI(2,pic_w-1)]+3*_aux[OC_MINI(3,pic_w-1)]+64>>7,255);
  639. }
  640. for(;x<pic_w-3;x+=2){
  641. tmp[x>>1]=OC_CLAMPI(0,3*(_aux[x-2]+_aux[x+3])-17*(_aux[x-1]+_aux[x+2])+
  642. 78*(_aux[x]+_aux[x+1])+64>>7,255);
  643. }
  644. for(;x<pic_w;x+=2){
  645. tmp[x>>1]=OC_CLAMPI(0,3*(_aux[x-2]+_aux[pic_w-1])-
  646. 17*(_aux[x-1]+_aux[OC_MINI(x+2,pic_w-1)])+
  647. 78*(_aux[x]+_aux[OC_MINI(x+1,pic_w-1)])+64>>7,255);
  648. }
  649. tmp+=c_w;
  650. _aux+=pic_w;
  651. }
  652. _aux-=pic_sz;
  653. tmp-=tmp_sz;
  654. /*Now do the vertical filtering.*/
  655. for(x=0;x<c_w;x++){
  656. for(y=0;y<OC_MINI(pic_h,2);y+=2){
  657. _dst[(y>>1)*c_w]=OC_CLAMPI(0,64*tmp[0]+78*tmp[OC_MINI(1,pic_h-1)*c_w]-
  658. 17*tmp[OC_MINI(2,pic_h-1)*c_w]+3*tmp[OC_MINI(3,pic_h-1)*c_w]+
  659. 64>>7,255);
  660. }
  661. for(;y<pic_h-3;y+=2){
  662. _dst[(y>>1)*c_w]=OC_CLAMPI(0,3*(tmp[(y-2)*c_w]+tmp[(y+3)*c_w])-
  663. 17*(tmp[(y-1)*c_w]+tmp[(y+2)*c_w])+78*(tmp[y*c_w]+tmp[(y+1)*c_w])+
  664. 64>>7,255);
  665. }
  666. for(;y<pic_h;y+=2){
  667. _dst[(y>>1)*c_w]=OC_CLAMPI(0,3*(tmp[(y-2)*c_w]+tmp[(pic_h-1)*c_w])-
  668. 17*(tmp[(y-1)*c_w]+tmp[OC_MINI(y+2,pic_h-1)*c_w])+
  669. 78*(tmp[y*c_w]+tmp[OC_MINI(y+1,pic_h-1)*c_w])+64>>7,255);
  670. }
  671. tmp++;
  672. _dst++;
  673. }
  674. _dst-=c_w;
  675. }
  676. }
  677. #endif
  678. /*No conversion function needed.*/
  679. static void y4m_convert_null(unsigned char *_dst,
  680. unsigned char *_aux){
  681. }
  682. static void id_file(char *f){
  683. FILE *test;
  684. unsigned char buffer[80];
  685. int ret;
  686. /* open it, look for magic */
  687. if(!strcmp(f,"-")){
  688. /* stdin */
  689. test=stdin;
  690. }else{
  691. test=fopen(f,"rb");
  692. if(!test){
  693. fprintf(stderr,"Unable to open file %s.\n",f);
  694. exit(1);
  695. }
  696. }
  697. ret=fread(buffer,1,4,test);
  698. if(ret<4){
  699. fprintf(stderr,"EOF determining file type of file %s.\n",f);
  700. exit(1);
  701. }
  702. if(!memcmp(buffer,"RIFF",4)){
  703. /* possible WAV file */
  704. if(audio){
  705. /* umm, we already have one */
  706. fprintf(stderr,"Multiple RIFF WAVE files specified on command line.\n");
  707. exit(1);
  708. }
  709. /* Parse the rest of the header */
  710. ret=fread(buffer,1,8,test);
  711. if(ret<8)goto riff_err;
  712. if(!memcmp(buffer+4,"WAVE",4)){
  713. while(!feof(test)){
  714. ret=fread(buffer,1,4,test);
  715. if(ret<4)goto riff_err;
  716. if(!memcmp("fmt",buffer,3)){
  717. /* OK, this is our audio specs chunk. Slurp it up. */
  718. ret=fread(buffer,1,20,test);
  719. if(ret<20)goto riff_err;
  720. if(memcmp(buffer+4,"\001\000",2)){
  721. fprintf(stderr,"The WAV file %s is in a compressed format; "
  722. "can't read it.\n",f);
  723. exit(1);
  724. }
  725. audio=test;
  726. audio_ch=buffer[6]+(buffer[7]<<8);
  727. audio_hz=buffer[8]+(buffer[9]<<8)+
  728. (buffer[10]<<16)+(buffer[11]<<24);
  729. if(buffer[18]+(buffer[19]<<8)!=16){
  730. fprintf(stderr,"Can only read 16 bit WAV files for now.\n");
  731. exit(1);
  732. }
  733. /* Now, align things to the beginning of the data */
  734. /* Look for 'dataxxxx' */
  735. while(!feof(test)){
  736. ret=fread(buffer,1,4,test);
  737. if(ret<4)goto riff_err;
  738. if(!memcmp("data",buffer,4)){
  739. /* We're there. Ignore the declared size for now. */
  740. ret=fread(buffer,1,4,test);
  741. if(ret<4)goto riff_err;
  742. if(!quiet){
  743. fprintf(stderr,"File %s is 16 bit %d channel %d Hz RIFF WAV audio.\n",
  744. f,audio_ch,audio_hz);
  745. }
  746. return;
  747. }
  748. }
  749. }
  750. }
  751. }
  752. fprintf(stderr,"Couldn't find WAVE data in RIFF file %s.\n",f);
  753. exit(1);
  754. }
  755. if(!memcmp(buffer,"YUV4",4)){
  756. /* possible YUV2MPEG2 format file */
  757. /* read until newline, or 80 cols, whichever happens first */
  758. int i;
  759. for(i=0;i<79;i++){
  760. ret=fread(buffer+i,1,1,test);
  761. if(ret<1)goto yuv_err;
  762. if(buffer[i]=='\n')break;
  763. }
  764. if(i==79){
  765. fprintf(stderr,"Error parsing %s header; not a YUV2MPEG2 file?\n",f);
  766. }
  767. buffer[i]='\0';
  768. if(!memcmp(buffer,"MPEG",4)){
  769. if(video){
  770. /* umm, we already have one */
  771. fprintf(stderr,"Multiple video files specified on command line.\n");
  772. exit(1);
  773. }
  774. if(buffer[4]!='2'){
  775. fprintf(stderr,"Incorrect YUV input file version; YUV4MPEG2 required.\n");
  776. }
  777. ret=y4m_parse_tags((char *)buffer+5);
  778. if(ret<0){
  779. fprintf(stderr,"Error parsing YUV4MPEG2 header in file %s.\n",f);
  780. exit(1);
  781. }
  782. if(interlace!='p'){
  783. fprintf(stderr,"Input video is interlaced; Theora handles only progressive scan\n");
  784. exit(1);
  785. }
  786. if(strcmp(chroma_type,"420")==0||strcmp(chroma_type,"420jpeg")==0){
  787. src_c_dec_h=dst_c_dec_h=src_c_dec_v=dst_c_dec_v=2;
  788. y4m_dst_buf_read_sz=pic_w*pic_h+2*((pic_w+1)/2)*((pic_h+1)/2);
  789. /*Natively supported: no conversion required.*/
  790. y4m_aux_buf_sz=y4m_aux_buf_read_sz=0;
  791. y4m_convert=y4m_convert_null;
  792. }
  793. else if(strcmp(chroma_type,"420mpeg2")==0){
  794. src_c_dec_h=dst_c_dec_h=src_c_dec_v=dst_c_dec_v=2;
  795. y4m_dst_buf_read_sz=pic_w*pic_h;
  796. /*Chroma filter required: read into the aux buf first.*/
  797. y4m_aux_buf_sz=y4m_aux_buf_read_sz=2*((pic_w+1)/2)*((pic_h+1)/2);
  798. y4m_convert=y4m_convert_42xmpeg2_42xjpeg;
  799. }
  800. else if(strcmp(chroma_type,"420paldv")==0){
  801. src_c_dec_h=dst_c_dec_h=src_c_dec_v=dst_c_dec_v=2;
  802. y4m_dst_buf_read_sz=pic_w*pic_h;
  803. /*Chroma filter required: read into the aux buf first.
  804. We need to make two filter passes, so we need some extra space in the
  805. aux buffer.*/
  806. y4m_aux_buf_sz=3*((pic_w+1)/2)*((pic_h+1)/2);
  807. y4m_aux_buf_read_sz=2*((pic_w+1)/2)*((pic_h+1)/2);
  808. y4m_convert=y4m_convert_42xpaldv_42xjpeg;
  809. }
  810. else if(strcmp(chroma_type,"422")==0){
  811. src_c_dec_h=dst_c_dec_h=2;
  812. src_c_dec_v=dst_c_dec_v=1;
  813. y4m_dst_buf_read_sz=pic_w*pic_h;
  814. /*Chroma filter required: read into the aux buf first.*/
  815. y4m_aux_buf_sz=y4m_aux_buf_read_sz=2*((pic_w+1)/2)*pic_h;
  816. y4m_convert=y4m_convert_42xmpeg2_42xjpeg;
  817. }
  818. else if(strcmp(chroma_type,"422jpeg")==0){
  819. src_c_dec_h=dst_c_dec_h=2;
  820. src_c_dec_v=dst_c_dec_v=1;
  821. y4m_dst_buf_read_sz=pic_w*pic_h+2*((pic_w+1)/2)*pic_h;
  822. /*Natively supported: no conversion required.*/
  823. y4m_aux_buf_sz=y4m_aux_buf_read_sz=0;
  824. y4m_convert=y4m_convert_null;
  825. }
  826. else if(strcmp(chroma_type,"411")==0){
  827. src_c_dec_h=4;
  828. /*We don't want to introduce any additional sub-sampling, so we
  829. promote 4:1:1 material to 4:2:2, as the closest format Theora can
  830. handle.*/
  831. dst_c_dec_h=2;
  832. src_c_dec_v=dst_c_dec_v=1;
  833. y4m_dst_buf_read_sz=pic_w*pic_h;
  834. /*Chroma filter required: read into the aux buf first.*/
  835. y4m_aux_buf_sz=y4m_aux_buf_read_sz=2*((pic_w+3)/4)*pic_h;
  836. y4m_convert=y4m_convert_411_422jpeg;
  837. }
  838. else if(strcmp(chroma_type,"444")==0){
  839. src_c_dec_h=dst_c_dec_h=src_c_dec_v=dst_c_dec_v=1;
  840. y4m_dst_buf_read_sz=pic_w*pic_h*3;
  841. y4m_aux_buf_sz=y4m_aux_buf_read_sz=0;
  842. y4m_convert=y4m_convert_null;
  843. }
  844. else if(strcmp(chroma_type,"444alpha")==0){
  845. src_c_dec_h=dst_c_dec_h=src_c_dec_v=dst_c_dec_v=1;
  846. y4m_dst_buf_read_sz=pic_w*pic_h*3;
  847. /*Read the extra alpha plane into the aux buf.
  848. It will be discarded.*/
  849. y4m_aux_buf_sz=y4m_aux_buf_read_sz=pic_w*pic_h;
  850. y4m_convert=y4m_convert_null;
  851. }
  852. else if(strcmp(chroma_type,"mono")==0){
  853. src_c_dec_h=src_c_dec_v=0;
  854. dst_c_dec_h=dst_c_dec_v=2;
  855. y4m_dst_buf_read_sz=pic_w*pic_h;
  856. y4m_aux_buf_sz=y4m_aux_buf_read_sz=0;
  857. y4m_convert=y4m_convert_mono_420jpeg;
  858. }
  859. else{
  860. fprintf(stderr,"Unknown chroma sampling type: %s\n",chroma_type);
  861. exit(1);
  862. }
  863. /*The size of the final frame buffers is always computed from the
  864. destination chroma decimation type.*/
  865. y4m_dst_buf_sz=pic_w*pic_h+2*((pic_w+dst_c_dec_h-1)/dst_c_dec_h)*
  866. ((pic_h+dst_c_dec_v-1)/dst_c_dec_v);
  867. video=test;
  868. if(!quiet){
  869. fprintf(stderr,"File %s is %dx%d %.02f fps %s video.\n",
  870. f,pic_w,pic_h,(double)video_fps_n/video_fps_d,chroma_type);
  871. }
  872. return;
  873. }
  874. }
  875. fprintf(stderr,"Input file %s is neither a WAV nor YUV4MPEG2 file.\n",f);
  876. exit(1);
  877. riff_err:
  878. fprintf(stderr,"EOF parsing RIFF file %s.\n",f);
  879. exit(1);
  880. yuv_err:
  881. fprintf(stderr,"EOF parsing YUV4MPEG2 file %s.\n",f);
  882. exit(1);
  883. }
  884. int spinner=0;
  885. char *spinascii="|/-\\";
  886. void spinnit(void){
  887. if(quiet){
  888. return;
  889. }
  890. spinner++;
  891. if(spinner==4)spinner=0;
  892. fprintf(stderr,"\r%c",spinascii[spinner]);
  893. }
  894. int fetch_and_process_audio(FILE *audio,ogg_page *audiopage,
  895. ogg_stream_state *vo,
  896. vorbis_dsp_state *vd,
  897. vorbis_block *vb,
  898. int audioflag){
  899. static ogg_int64_t samples_sofar=0;
  900. ogg_packet op;
  901. int i,j;
  902. ogg_int64_t beginsample = audio_hz*(begin_sec+begin_usec*.000001);
  903. ogg_int64_t endsample = audio_hz*(end_sec+end_usec*.000001);
  904. while(audio && !audioflag){
  905. /* process any audio already buffered */
  906. spinnit();
  907. if(ogg_stream_pageout(vo,audiopage)>0) return 1;
  908. if(ogg_stream_eos(vo))return 0;
  909. {
  910. /* read and process more audio */
  911. signed char readbuffer[4096];
  912. signed char *readptr=readbuffer;
  913. int toread=4096/2/audio_ch;
  914. int bytesread=fread(readbuffer,1,toread*2*audio_ch,audio);
  915. int sampread=bytesread/2/audio_ch;
  916. float **vorbis_buffer;
  917. int count=0;
  918. if(bytesread<=0 ||
  919. (samples_sofar>=endsample && endsample>0)){
  920. /* end of file. this can be done implicitly, but it's
  921. easier to see here in non-clever fashion. Tell the
  922. library we're at end of stream so that it can handle the
  923. last frame and mark end of stream in the output properly */
  924. vorbis_analysis_wrote(vd,0);
  925. }else{
  926. if(samples_sofar < beginsample){
  927. if(samples_sofar+sampread > beginsample){
  928. readptr += (beginsample-samples_sofar)*2*audio_ch;
  929. sampread += samples_sofar-beginsample;
  930. samples_sofar = sampread+beginsample;
  931. }else{
  932. samples_sofar += sampread;
  933. sampread = 0;
  934. }
  935. }else{
  936. samples_sofar += sampread;
  937. }
  938. if(samples_sofar > endsample && endsample > 0)
  939. sampread-= (samples_sofar - endsample);
  940. if(sampread>0){
  941. vorbis_buffer=vorbis_analysis_buffer(vd,sampread);
  942. /* uninterleave samples */
  943. for(i=0;i<sampread;i++){
  944. for(j=0;j<audio_ch;j++){
  945. vorbis_buffer[j][i]=((readptr[count+1]<<8)|
  946. (0x00ff&(int)readptr[count]))/32768.f;
  947. count+=2;
  948. }
  949. }
  950. vorbis_analysis_wrote(vd,sampread);
  951. }
  952. }
  953. while(vorbis_analysis_blockout(vd,vb)==1){
  954. /* analysis, assume we want to use bitrate management */
  955. vorbis_analysis(vb,NULL);
  956. vorbis_bitrate_addblock(vb);
  957. /* weld packets into the bitstream */
  958. while(vorbis_bitrate_flushpacket(vd,&op))
  959. ogg_stream_packetin(vo,&op);
  960. }
  961. }
  962. }
  963. return audioflag;
  964. }
  965. static int frame_state=-1;
  966. static ogg_int64_t frames=0;
  967. static unsigned char *yuvframe[3];
  968. static th_ycbcr_buffer ycbcr;
  969. int fetch_and_process_video_packet(FILE *video,FILE *twopass_file,int passno,
  970. th_enc_ctx *td,ogg_packet *op){
  971. int ret;
  972. int pic_sz;
  973. int c_w;
  974. int c_h;
  975. int c_sz;
  976. ogg_int64_t beginframe;
  977. ogg_int64_t endframe;
  978. spinnit();
  979. beginframe=video_fps_n*(begin_sec+begin_usec*.000001)/video_fps_d;
  980. endframe=video_fps_n*(end_sec+end_usec*.000001)/video_fps_d;
  981. if(frame_state==-1){
  982. /* initialize the double frame buffer */
  983. yuvframe[0]=(unsigned char *)malloc(y4m_dst_buf_sz);
  984. yuvframe[1]=(unsigned char *)malloc(y4m_dst_buf_sz);
  985. yuvframe[2]=(unsigned char *)malloc(y4m_aux_buf_sz);
  986. frame_state=0;
  987. }
  988. pic_sz=pic_w*pic_h;
  989. c_w=(pic_w+dst_c_dec_h-1)/dst_c_dec_h;
  990. c_h=(pic_h+dst_c_dec_v-1)/dst_c_dec_v;
  991. c_sz=c_w*c_h;
  992. /* read and process more video */
  993. /* video strategy reads one frame ahead so we know when we're
  994. at end of stream and can mark last video frame as such
  995. (vorbis audio has to flush one frame past last video frame
  996. due to overlap and thus doesn't need this extra work */
  997. /* have two frame buffers full (if possible) before
  998. proceeding. after first pass and until eos, one will
  999. always be full when we get here */
  1000. for(;frame_state<2 && (frames<endframe || endframe<0);){
  1001. char c,frame[6];
  1002. int ret=fread(frame,1,6,video);
  1003. /* match and skip the frame header */
  1004. if(ret<6)break;
  1005. if(memcmp(frame,"FRAME",5)){
  1006. fprintf(stderr,"Loss of framing in YUV input data\n");
  1007. exit(1);
  1008. }
  1009. if(frame[5]!='\n'){
  1010. int j;
  1011. for(j=0;j<79;j++)
  1012. if(fread(&c,1,1,video)&&c=='\n')break;
  1013. if(j==79){
  1014. fprintf(stderr,"Error parsing YUV frame header\n");
  1015. exit(1);
  1016. }
  1017. }
  1018. /*Read the frame data that needs no conversion.*/
  1019. if(fread(yuvframe[frame_state],1,y4m_dst_buf_read_sz,video)!=
  1020. y4m_dst_buf_read_sz){
  1021. fprintf(stderr,"Error reading YUV frame data.\n");
  1022. exit(1);
  1023. }
  1024. /*Read the frame data that does need conversion.*/
  1025. if(fread(yuvframe[2],1,y4m_aux_buf_read_sz,video)!=y4m_aux_buf_read_sz){
  1026. fprintf(stderr,"Error reading YUV frame data.\n");
  1027. exit(1);
  1028. }
  1029. /*Now convert the just read frame.*/
  1030. (*y4m_convert)(yuvframe[frame_state],yuvframe[2]);
  1031. frames++;
  1032. if(frames>=beginframe)
  1033. frame_state++;
  1034. }
  1035. /* check to see if there are dupes to flush */
  1036. if(th_encode_packetout(td,frame_state<1,op)>0)return 1;
  1037. if(frame_state<1){
  1038. /* can't get here unless YUV4MPEG stream has no video */
  1039. fprintf(stderr,"Video input contains no frames.\n");
  1040. exit(1);
  1041. }
  1042. /* Theora is a one-frame-in,one-frame-out system; submit a frame
  1043. for compression and pull out the packet */
  1044. /* in two-pass mode's second pass, we need to submit first-pass data */
  1045. if(passno==2){
  1046. for(;;){
  1047. static unsigned char buffer[80];
  1048. static int buf_pos;
  1049. int bytes;
  1050. /*Ask the encoder how many bytes it would like.*/
  1051. bytes=th_encode_ctl(td,TH_ENCCTL_2PASS_IN,NULL,0);
  1052. if(bytes<0){
  1053. fprintf(stderr,"Error submitting pass data in second pass.\n");
  1054. exit(1);
  1055. }
  1056. /*If it's got enough, stop.*/
  1057. if(bytes==0)break;
  1058. /*Read in some more bytes, if necessary.*/
  1059. if(bytes>80-buf_pos)bytes=80-buf_pos;
  1060. if(bytes>0&&fread(buffer+buf_pos,1,bytes,twopass_file)<bytes){
  1061. fprintf(stderr,"Could not read frame data from two-pass data file!\n");
  1062. exit(1);
  1063. }
  1064. /*And pass them off.*/
  1065. ret=th_encode_ctl(td,TH_ENCCTL_2PASS_IN,buffer,bytes);
  1066. if(ret<0){
  1067. fprintf(stderr,"Error submitting pass data in second pass.\n");
  1068. exit(1);
  1069. }
  1070. /*If the encoder consumed the whole buffer, reset it.*/
  1071. if(ret>=bytes)buf_pos=0;
  1072. /*Otherwise remember how much it used.*/
  1073. else buf_pos+=ret;
  1074. }
  1075. }
  1076. /*We submit the buffer using the size of the picture region.
  1077. libtheora will pad the picture region out to the full frame size for us,
  1078. whether we pass in a full frame or not.*/
  1079. ycbcr[0].width=pic_w;
  1080. ycbcr[0].height=pic_h;
  1081. ycbcr[0].stride=pic_w;
  1082. ycbcr[0].data=yuvframe[0];
  1083. ycbcr[1].width=c_w;
  1084. ycbcr[1].height=c_h;
  1085. ycbcr[1].stride=c_w;
  1086. ycbcr[1].data=yuvframe[0]+pic_sz;
  1087. ycbcr[2].width=c_w;
  1088. ycbcr[2].height=c_h;
  1089. ycbcr[2].stride=c_w;
  1090. ycbcr[2].data=yuvframe[0]+pic_sz+c_sz;
  1091. th_encode_ycbcr_in(td,ycbcr);
  1092. {
  1093. unsigned char *temp=yuvframe[0];
  1094. yuvframe[0]=yuvframe[1];
  1095. yuvframe[1]=temp;
  1096. frame_state--;
  1097. }
  1098. /* in two-pass mode's first pass we need to extract and save the pass data */
  1099. if(passno==1){
  1100. unsigned char *buffer;
  1101. int bytes = th_encode_ctl(td, TH_ENCCTL_2PASS_OUT, &buffer, sizeof(buffer));
  1102. if(bytes<0){
  1103. fprintf(stderr,"Could not read two-pass data from encoder.\n");
  1104. exit(1);
  1105. }
  1106. if(fwrite(buffer,1,bytes,twopass_file)<bytes){
  1107. fprintf(stderr,"Unable to write to two-pass data file.\n");
  1108. exit(1);
  1109. }
  1110. fflush(twopass_file);
  1111. }
  1112. /* if there was only one frame, it's the last in the stream */
  1113. ret = th_encode_packetout(td,frame_state<1,op);
  1114. if(passno==1 && frame_state<1){
  1115. /* need to read the final (summary) packet */
  1116. unsigned char *buffer;
  1117. int bytes = th_encode_ctl(td, TH_ENCCTL_2PASS_OUT, &buffer, sizeof(buffer));
  1118. if(bytes<0){
  1119. fprintf(stderr,"Could not read two-pass summary data from encoder.\n");
  1120. exit(1);
  1121. }
  1122. if(fseek(twopass_file,0,SEEK_SET)<0){
  1123. fprintf(stderr,"Unable to seek in two-pass data file.\n");
  1124. exit(1);
  1125. }
  1126. if(fwrite(buffer,1,bytes,twopass_file)<bytes){
  1127. fprintf(stderr,"Unable to write to two-pass data file.\n");
  1128. exit(1);
  1129. }
  1130. fflush(twopass_file);
  1131. }
  1132. return ret;
  1133. }
  1134. int fetch_and_process_video(FILE *video,ogg_page *videopage,
  1135. ogg_stream_state *to,th_enc_ctx *td,FILE *twopass_file,int passno,
  1136. int videoflag){
  1137. ogg_packet op;
  1138. int ret;
  1139. /* is there a video page flushed? If not, work until there is. */
  1140. while(!videoflag){
  1141. if(ogg_stream_pageout(to,videopage)>0) return 1;
  1142. if(ogg_stream_eos(to)) return 0;
  1143. ret=fetch_and_process_video_packet(video,twopass_file,passno,td,&op);
  1144. if(ret<=0)return 0;
  1145. ogg_stream_packetin(to,&op);
  1146. }
  1147. return videoflag;
  1148. }
  1149. static int ilog(unsigned _v){
  1150. int ret;
  1151. for(ret=0;_v;ret++)_v>>=1;
  1152. return ret;
  1153. }
  1154. static int parse_time(long *_sec,long *_usec,const char *_optarg){
  1155. double secf;
  1156. long secl;
  1157. const char *pos;
  1158. char *end;
  1159. int err;
  1160. err=0;
  1161. secl=0;
  1162. pos=strchr(_optarg,':');
  1163. if(pos!=NULL){
  1164. char *pos2;
  1165. secl=strtol(_optarg,&end,10)*60;
  1166. err|=pos!=end;
  1167. pos2=strchr(++pos,':');
  1168. if(pos2!=NULL){
  1169. secl=(secl+strtol(pos,&end,10))*60;
  1170. err|=pos2!=end;
  1171. pos=pos2+1;
  1172. }
  1173. }
  1174. else pos=_optarg;
  1175. secf=strtod(pos,&end);
  1176. if(err||*end!='\0')return -1;
  1177. *_sec=secl+(long)floor(secf);
  1178. *_usec=(long)((secf-floor(secf))*1E6+0.5);
  1179. return 0;
  1180. }
  1181. int main(int argc,char *argv[]){
  1182. int c,long_option_index,ret;
  1183. ogg_stream_state to; /* take physical pages, weld into a logical
  1184. stream of packets */
  1185. ogg_stream_state vo; /* take physical pages, weld into a logical
  1186. stream of packets */
  1187. ogg_page og; /* one Ogg bitstream page. Vorbis packets are inside */
  1188. ogg_packet op; /* one raw packet of data for decode */
  1189. th_enc_ctx *td;
  1190. th_info ti;
  1191. th_comment tc;
  1192. vorbis_info vi; /* struct that stores all the static vorbis bitstream
  1193. settings */
  1194. vorbis_comment vc; /* struct that stores all the user comments */
  1195. vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */
  1196. vorbis_block vb; /* local working space for packet->PCM decode */
  1197. int speed=-1;
  1198. int audioflag=0;
  1199. int videoflag=0;
  1200. int akbps=0;
  1201. int vkbps=0;
  1202. int soft_target=0;
  1203. ogg_int64_t audio_bytesout=0;
  1204. ogg_int64_t video_bytesout=0;
  1205. double timebase;
  1206. FILE *outfile = stdout;
  1207. FILE *twopass_file = NULL;
  1208. fpos_t video_rewind_pos;
  1209. int twopass=0;
  1210. int passno;
  1211. clock_t clock_start=clock();
  1212. clock_t clock_end;
  1213. double elapsed;
  1214. #ifdef _WIN32 /* We need to set stdin/stdout to binary mode. Damn windows. */
  1215. /* if we were reading/writing a file, it would also need to in
  1216. binary mode, eg, fopen("file.wav","wb"); */
  1217. /* Beware the evil ifdef. We avoid these where we can, but this one we
  1218. cannot. Don't add any more, you'll probably go to hell if you do. */
  1219. _setmode( _fileno( stdin ), _O_BINARY );
  1220. _setmode( _fileno( stdout ), _O_BINARY );
  1221. #endif
  1222. while((c=getopt_long(argc,argv,optstring,options,&long_option_index))!=EOF){
  1223. switch(c){
  1224. case 'o':
  1225. outfile=fopen(optarg,"wb");
  1226. if(outfile==NULL){
  1227. fprintf(stderr,"Unable to open output file '%s'\n", optarg);
  1228. exit(1);
  1229. }
  1230. break;;
  1231. case 'a':
  1232. audio_q=(float)(atof(optarg)*.099);
  1233. if(audio_q<-.1 || audio_q>1){
  1234. fprintf(stderr,"Illegal audio quality (choose -1 through 10)\n");
  1235. exit(1);
  1236. }
  1237. audio_r=-1;
  1238. break;
  1239. case 'v':
  1240. video_q=(int)rint(6.3*atof(optarg));
  1241. if(video_q<0 || video_q>63){
  1242. fprintf(stderr,"Illegal video quality (choose 0 through 10)\n");
  1243. exit(1);
  1244. }
  1245. break;
  1246. case 'A':
  1247. audio_r=(int)(atof(optarg)*1000);
  1248. if(audio_q<0){
  1249. fprintf(stderr,"Illegal audio quality (choose > 0 please)\n");
  1250. exit(1);
  1251. }
  1252. audio_q=-99;
  1253. break;
  1254. case 'V':
  1255. video_r=(int)rint(atof(optarg)*1000);
  1256. if(video_r<1){
  1257. fprintf(stderr,"Illegal video bitrate (choose > 0 please)\n");
  1258. exit(1);
  1259. }
  1260. break;
  1261. case '\1':
  1262. soft_target=1;
  1263. break;
  1264. case 's':
  1265. video_par_n=(int)rint(atof(optarg));
  1266. break;
  1267. case 'S':
  1268. video_par_d=(int)rint(atof(optarg));
  1269. break;
  1270. case 'f':
  1271. video_fps_n=(int)rint(atof(optarg));
  1272. break;
  1273. case 'F':
  1274. video_fps_d=(int)rint(atof(optarg));
  1275. break;
  1276. case 'q':
  1277. quiet=1;
  1278. break;
  1279. case 'c':
  1280. vp3_compatible=1;
  1281. break;
  1282. case 'k':
  1283. keyframe_frequency=rint(atof(optarg));
  1284. if(keyframe_frequency<1 || keyframe_frequency>2147483647){
  1285. fprintf(stderr,"Illegal keyframe frequency\n");
  1286. exit(1);
  1287. }
  1288. break;
  1289. case 'd':
  1290. buf_delay=atoi(optarg);
  1291. if(buf_delay<=0){
  1292. fprintf(stderr,"Illegal buffer delay\n");
  1293. exit(1);
  1294. }
  1295. break;
  1296. case 'z':
  1297. speed=atoi(optarg);
  1298. if(speed<0){
  1299. fprintf(stderr,"Illegal speed level\n");
  1300. exit(1);
  1301. }
  1302. break;
  1303. case 'b':
  1304. {
  1305. if(parse_time(&begin_sec,&begin_usec,optarg)<0){
  1306. fprintf(stderr,"Error parsing begin time '%s'.\n",optarg);
  1307. exit(1);
  1308. }
  1309. }
  1310. break;
  1311. case 'e':
  1312. {
  1313. if(parse_time(&end_sec,&end_usec,optarg)<0){
  1314. fprintf(stderr,"Error parsing end time '%s'.\n",optarg);
  1315. exit(1);
  1316. }
  1317. }
  1318. break;
  1319. case '\2':
  1320. twopass=3; /* perform both passes */
  1321. twopass_file=tmpfile();
  1322. if(!twopass_file){
  1323. fprintf(stderr,"Unable to open temporary file for twopass data\n");
  1324. exit(1);
  1325. }
  1326. break;
  1327. case '\3':
  1328. twopass=1; /* perform first pass */
  1329. twopass_file=fopen(optarg,"wb");
  1330. if(!twopass_file){
  1331. fprintf(stderr,"Unable to open \'%s\' for twopass data\n",optarg);
  1332. exit(1);
  1333. }
  1334. break;
  1335. case '\4':
  1336. twopass=2; /* perform second pass */
  1337. twopass_file=fopen(optarg,"rb");
  1338. if(!twopass_file){
  1339. fprintf(stderr,"Unable to open twopass data file \'%s\'",optarg);
  1340. exit(1);
  1341. }
  1342. break;
  1343. #if defined(OC_COLLECT_METRICS)
  1344. case 'm':
  1345. if(th_encode_ctl(NULL,TH_ENCCTL_SET_METRICS_FILE,
  1346. optarg,strlen(optarg)+1)){
  1347. fprintf(stderr,"Unable to set metrics collection file name.\n");
  1348. fprintf(stderr,"libtheora not compiled with OC_COLLECT_METRICS?\n");
  1349. exit(1);
  1350. }
  1351. break;
  1352. #endif
  1353. default:
  1354. usage();
  1355. }
  1356. }
  1357. if(soft_target){
  1358. if(video_r<=0){
  1359. fprintf(stderr,"Soft rate target (--soft-target) requested without a bitrate (-V).\n");
  1360. exit(1);
  1361. }
  1362. if(video_q==-1)
  1363. video_q=0;
  1364. }else{
  1365. if(video_q==-1){
  1366. if(video_r>0)
  1367. video_q=0;
  1368. else
  1369. video_q=48;
  1370. }
  1371. }
  1372. if(keyframe_frequency<=0){
  1373. /*Use a default keyframe frequency of 64 for 1-pass (streaming) mode, and
  1374. 256 for two-pass mode.*/
  1375. keyframe_frequency=twopass?256:64;
  1376. }
  1377. while(optind<argc){
  1378. /* assume that anything following the options must be a filename */
  1379. id_file(argv[optind]);
  1380. optind++;
  1381. }
  1382. if(twopass==3){
  1383. /* verify that the input is seekable! */
  1384. if(video){
  1385. if(fseek(video,0,SEEK_CUR)){
  1386. fprintf(stderr,"--two-pass (automatic two-pass) requires the video input\n"
  1387. "to be seekable. For non-seekable input, encoder_example\n"
  1388. "must be run twice, first with the --first-pass option, then\n"
  1389. "with the --second-pass option.\n\n");
  1390. exit(1);
  1391. }
  1392. if(fgetpos(video,&video_rewind_pos)<0){
  1393. fprintf(stderr,"Unable to determine start position of video data.\n");
  1394. exit(1);
  1395. }
  1396. }
  1397. }
  1398. /* Set up Ogg output stream */
  1399. srand(time(NULL));
  1400. ogg_stream_init(&to,rand()); /* oops, add one to the above */
  1401. /* initialize Vorbis assuming we have audio to compress. */
  1402. if(audio && twopass!=1){
  1403. ogg_stream_init(&vo,rand());
  1404. vorbis_info_init(&vi);
  1405. if(audio_q>-99)
  1406. ret = vorbis_encode_init_vbr(&vi,audio_ch,audio_hz,audio_q);
  1407. else
  1408. ret = vorbis_encode_init(&vi,audio_ch,audio_hz,-1,
  1409. (int)(64870*(ogg_int64_t)audio_r>>16),-1);
  1410. if(ret){
  1411. fprintf(stderr,"The Vorbis encoder could not set up a mode according to\n"
  1412. "the requested quality or bitrate.\n\n");
  1413. exit(1);
  1414. }
  1415. vorbis_comment_init(&vc);
  1416. vorbis_analysis_init(&vd,&vi);
  1417. vorbis_block_init(&vd,&vb);
  1418. }
  1419. for(passno=(twopass==3?1:twopass);passno<=(twopass==3?2:twopass);passno++){
  1420. /* Set up Theora encoder */
  1421. if(!video){
  1422. fprintf(stderr,"No video files submitted for compression?\n");
  1423. exit(1);
  1424. }
  1425. /* Theora has a divisible-by-sixteen restriction for the encoded frame size */
  1426. /* scale the picture size up to the nearest /16 and calculate offsets */
  1427. frame_w=pic_w+15&~0xF;
  1428. frame_h=pic_h+15&~0xF;
  1429. /*Force the offsets to be even so that chroma samples line up like we
  1430. expect.*/
  1431. pic_x=frame_w-pic_w>>1&~1;
  1432. pic_y=frame_h-pic_h>>1&~1;
  1433. th_info_init(&ti);
  1434. ti.frame_width=frame_w;
  1435. ti.frame_height=frame_h;
  1436. ti.pic_width=pic_w;
  1437. ti.pic_height=pic_h;
  1438. ti.pic_x=pic_x;
  1439. ti.pic_y=pic_y;
  1440. ti.fps_numerator=video_fps_n;
  1441. ti.fps_denominator=video_fps_d;
  1442. ti.aspect_numerator=video_par_n;
  1443. ti.aspect_denominator=video_par_d;
  1444. ti.colorspace=TH_CS_UNSPECIFIED;
  1445. /*Account for the Ogg page overhead.
  1446. This is 1 byte per 255 for lacing values, plus 26 bytes per 4096 bytes for
  1447. the page header, plus approximately 1/2 byte per packet (not accounted for
  1448. here).*/
  1449. ti.target_bitrate=(int)(64870*(ogg_int64_t)video_r>>16);
  1450. ti.quality=video_q;
  1451. ti.keyframe_granule_shift=ilog(keyframe_frequency-1);
  1452. if(dst_c_dec_h==2){
  1453. if(dst_c_dec_v==2)ti.pixel_fmt=TH_PF_420;
  1454. else ti.pixel_fmt=TH_PF_422;
  1455. }
  1456. else ti.pixel_fmt=TH_PF_444;
  1457. td=th_encode_alloc(&ti);
  1458. th_info_clear(&ti);
  1459. if(td==NULL){
  1460. fprintf(stderr,"Error: Could not create an encoder instance.\n");
  1461. fprintf(stderr,"Check that video parameters are valid.\n");
  1462. exit(1);
  1463. }
  1464. /* setting just the granule shift only allows power-of-two keyframe
  1465. spacing. Set the actual requested spacing. */
  1466. ret=th_encode_ctl(td,TH_ENCCTL_SET_KEYFRAME_FREQUENCY_FORCE,
  1467. &keyframe_frequency,sizeof(keyframe_frequency-1));
  1468. if(ret<0){
  1469. fprintf(stderr,"Could not set keyframe interval to %d.\n",(int)keyframe_frequency);
  1470. }
  1471. if(vp3_compatible){
  1472. ret=th_encode_ctl(td,TH_ENCCTL_SET_VP3_COMPATIBLE,&vp3_compatible,
  1473. sizeof(vp3_compatible));
  1474. if(ret<0||!vp3_compatible){
  1475. fprintf(stderr,"Could not enable strict VP3 compatibility.\n");
  1476. if(ret>=0){
  1477. fprintf(stderr,"Ensure your source format is supported by VP3.\n");
  1478. fprintf(stderr,
  1479. "(4:2:0 pixel format, width and height multiples of 16).\n");
  1480. }
  1481. }
  1482. }
  1483. if(soft_target){
  1484. /* reverse the rate control flags to favor a 'long time' strategy */
  1485. int arg = TH_RATECTL_CAP_UNDERFLOW;
  1486. ret=th_encode_ctl(td,TH_ENCCTL_SET_RATE_FLAGS,&arg,sizeof(arg));
  1487. if(ret<0)
  1488. fprintf(stderr,"Could not set encoder flags for --soft-target\n");
  1489. /* Default buffer control is overridden on two-pass */
  1490. if(!twopass&&buf_delay<0){
  1491. if((keyframe_frequency*7>>1) > 5*video_fps_n/video_fps_d)
  1492. arg=keyframe_frequency*7>>1;
  1493. else
  1494. arg=5*video_fps_n/video_fps_d;
  1495. ret=th_encode_ctl(td,TH_ENCCTL_SET_RATE_BUFFER,&arg,sizeof(arg));
  1496. if(ret<0)
  1497. fprintf(stderr,"Could not set rate control buffer for --soft-target\n");
  1498. }
  1499. }
  1500. /* set up two-pass if needed */
  1501. if(passno==1){
  1502. unsigned char *buffer;
  1503. int bytes;
  1504. bytes=th_encode_ctl(td,TH_ENCCTL_2PASS_OUT,&buffer,sizeof(buffer));
  1505. if(bytes<0){
  1506. fprintf(stderr,"Could not set up the first pass of two-pass mode.\n");
  1507. fprintf(stderr,"Did you remember to specify an estimated bitrate?\n");
  1508. exit(1);
  1509. }
  1510. /*Perform a seek test to ensure we can overwrite this placeholder data at
  1511. the end; this is better than letting the user sit through a whole
  1512. encode only to find out their pass 1 file is useless at the end.*/
  1513. if(fseek(twopass_file,0,SEEK_SET)<0){
  1514. fprintf(stderr,"Unable to seek in two-pass data file.\n");
  1515. exit(1);
  1516. }
  1517. if(fwrite(buffer,1,bytes,twopass_file)<bytes){
  1518. fprintf(stderr,"Unable to write to two-pass data file.\n");
  1519. exit(1);
  1520. }
  1521. fflush(twopass_file);
  1522. }
  1523. if(passno==2){
  1524. /*Enable the second pass here.
  1525. We make this call just to set the encoder into 2-pass mode, because
  1526. by default enabling two-pass sets the buffer delay to the whole file
  1527. (because there's no way to explicitly request that behavior).
  1528. If we waited until we were actually encoding, it would overwite our
  1529. settings.*/
  1530. if(th_encode_ctl(td,TH_ENCCTL_2PASS_IN,NULL,0)<0){
  1531. fprintf(stderr,"Could not set up the second pass of two-pass mode.\n");
  1532. exit(1);
  1533. }
  1534. if(twopass==3){
  1535. /* 'automatic' second pass */
  1536. if(fsetpos(video,&video_rewind_pos)<0){
  1537. fprintf(stderr,"Could not rewind video input file for second pass!\n");
  1538. exit(1);
  1539. }
  1540. if(fseek(twopass_file,0,SEEK_SET)<0){
  1541. fprintf(stderr,"Unable to seek in two-pass data file.\n");
  1542. exit(1);
  1543. }
  1544. frame_state=0;
  1545. frames=0;
  1546. }
  1547. }
  1548. /*Now we can set the buffer delay if the user requested a non-default one
  1549. (this has to be done after two-pass is enabled).*/
  1550. if(passno!=1&&buf_delay>=0){
  1551. ret=th_encode_ctl(td,TH_ENCCTL_SET_RATE_BUFFER,
  1552. &buf_delay,sizeof(buf_delay));
  1553. if(ret<0){
  1554. fprintf(stderr,"Warning: could not set desired buffer delay.\n");
  1555. }
  1556. }
  1557. /*Speed should also be set after the current encoder mode is established,
  1558. since the available speed levels may change depending.*/
  1559. if(speed>=0){
  1560. int speed_max;
  1561. int ret;
  1562. ret=th_encode_ctl(td,TH_ENCCTL_GET_SPLEVEL_MAX,
  1563. &speed_max,sizeof(speed_max));
  1564. if(ret<0){
  1565. fprintf(stderr,"Warning: could not determine maximum speed level.\n");
  1566. speed_max=0;
  1567. }
  1568. ret=th_encode_ctl(td,TH_ENCCTL_SET_SPLEVEL,&speed,sizeof(speed));
  1569. if(ret<0){
  1570. fprintf(stderr,"Warning: could not set speed level to %i of %i\n",
  1571. speed,speed_max);
  1572. if(speed>speed_max){
  1573. fprintf(stderr,"Setting it to %i instead\n",speed_max);
  1574. }
  1575. ret=th_encode_ctl(td,TH_ENCCTL_SET_SPLEVEL,
  1576. &speed_max,sizeof(speed_max));
  1577. if(ret<0){
  1578. fprintf(stderr,"Warning: could not set speed level to %i of %i\n",
  1579. speed_max,speed_max);
  1580. }
  1581. }
  1582. }
  1583. /* write the bitstream header packets with proper page interleave */
  1584. th_comment_init(&tc);
  1585. /* first packet will get its own page automatically */
  1586. if(th_encode_flushheader(td,&tc,&op)<=0){
  1587. fprintf(stderr,"Internal Theora library error.\n");
  1588. exit(1);
  1589. }
  1590. if(passno!=1){
  1591. ogg_stream_packetin(&to,&op);
  1592. if(ogg_stream_pageout(&to,&og)!=1){
  1593. fprintf(stderr,"Internal Ogg library error.\n");
  1594. exit(1);
  1595. }
  1596. fwrite(og.header,1,og.header_len,outfile);
  1597. fwrite(og.body,1,og.body_len,outfile);
  1598. }
  1599. /* create the remaining theora headers */
  1600. for(;;){
  1601. ret=th_encode_flushheader(td,&tc,&op);
  1602. if(ret<0){
  1603. fprintf(stderr,"Internal Theora library error.\n");
  1604. exit(1);
  1605. }
  1606. else if(!ret)break;
  1607. if(passno!=1)ogg_stream_packetin(&to,&op);
  1608. }
  1609. if(audio && passno!=1){
  1610. ogg_packet header;
  1611. ogg_packet header_comm;
  1612. ogg_packet header_code;
  1613. vorbis_analysis_headerout(&vd,&vc,&header,&header_comm,&header_code);
  1614. ogg_stream_packetin(&vo,&header); /* automatically placed in its own
  1615. page */
  1616. if(ogg_stream_pageout(&vo,&og)!=1){
  1617. fprintf(stderr,"Internal Ogg library error.\n");
  1618. exit(1);
  1619. }
  1620. fwrite(og.header,1,og.header_len,outfile);
  1621. fwrite(og.body,1,og.body_len,outfile);
  1622. /* remaining vorbis header packets */
  1623. ogg_stream_packetin(&vo,&header_comm);
  1624. ogg_stream_packetin(&vo,&header_code);
  1625. }
  1626. /* Flush the rest of our headers. This ensures
  1627. the actual data in each stream will start
  1628. on a new page, as per spec. */
  1629. if(passno!=1){
  1630. for(;;){
  1631. int result = ogg_stream_flush(&to,&og);
  1632. if(result<0){
  1633. /* can't get here */
  1634. fprintf(stderr,"Internal Ogg library error.\n");
  1635. exit(1);
  1636. }
  1637. if(result==0)break;
  1638. fwrite(og.header,1,og.header_len,outfile);
  1639. fwrite(og.body,1,og.body_len,outfile);
  1640. }
  1641. }
  1642. if(audio && passno!=1){
  1643. for(;;){
  1644. int result=ogg_stream_flush(&vo,&og);
  1645. if(result<0){
  1646. /* can't get here */
  1647. fprintf(stderr,"Internal Ogg library error.\n");
  1648. exit(1);
  1649. }
  1650. if(result==0)break;
  1651. fwrite(og.header,1,og.header_len,outfile);
  1652. fwrite(og.body,1,og.body_len,outfile);
  1653. }
  1654. }
  1655. /* setup complete. Raw processing loop */
  1656. if(!quiet){
  1657. switch(passno){
  1658. case 0: case 2:
  1659. fprintf(stderr,"\rCompressing.... \n");
  1660. break;
  1661. case 1:
  1662. fprintf(stderr,"\rScanning first pass.... \n");
  1663. break;
  1664. }
  1665. }
  1666. for(;;){
  1667. int audio_or_video=-1;
  1668. if(passno==1){
  1669. ogg_packet op;
  1670. int ret=fetch_and_process_video_packet(video,twopass_file,passno,td,&op);
  1671. if(ret<0)break;
  1672. if(op.e_o_s)break; /* end of stream */
  1673. timebase=th_granule_time(td,op.granulepos);
  1674. audio_or_video=1;
  1675. }else{
  1676. double audiotime;
  1677. double videotime;
  1678. ogg_page audiopage;
  1679. ogg_page videopage;
  1680. /* is there an audio page flushed? If not, fetch one if possible */
  1681. audioflag=fetch_and_process_audio(audio,&audiopage,&vo,&vd,&vb,audioflag);
  1682. /* is there a video page flushed? If not, fetch one if possible */
  1683. videoflag=fetch_and_process_video(video,&videopage,&to,td,twopass_file,passno,videoflag);
  1684. /* no pages of either? Must be end of stream. */
  1685. if(!audioflag && !videoflag)break;
  1686. /* which is earlier; the end of the audio page or the end of the
  1687. video page? Flush the earlier to stream */
  1688. audiotime=
  1689. audioflag?vorbis_granule_time(&vd,ogg_page_granulepos(&audiopage)):-1;
  1690. videotime=
  1691. videoflag?th_granule_time(td,ogg_page_granulepos(&videopage)):-1;
  1692. if(!audioflag){
  1693. audio_or_video=1;
  1694. } else if(!videoflag) {
  1695. audio_or_video=0;
  1696. } else {
  1697. if(audiotime<videotime)
  1698. audio_or_video=0;
  1699. else
  1700. audio_or_video=1;
  1701. }
  1702. if(audio_or_video==1){
  1703. /* flush a video page */
  1704. video_bytesout+=fwrite(videopage.header,1,videopage.header_len,outfile);
  1705. video_bytesout+=fwrite(videopage.body,1,videopage.body_len,outfile);
  1706. videoflag=0;
  1707. timebase=videotime;
  1708. }else{
  1709. /* flush an audio page */
  1710. audio_bytesout+=fwrite(audiopage.header,1,audiopage.header_len,outfile);
  1711. audio_bytesout+=fwrite(audiopage.body,1,audiopage.body_len,outfile);
  1712. audioflag=0;
  1713. timebase=audiotime;
  1714. }
  1715. }
  1716. if(!quiet&&timebase>0){
  1717. int hundredths=(int)(timebase*100-(long)timebase*100);
  1718. int seconds=(long)timebase%60;
  1719. int minutes=((long)timebase/60)%60;
  1720. int hours=(long)timebase/3600;
  1721. if(audio_or_video)vkbps=(int)rint(video_bytesout*8./timebase*.001);
  1722. else akbps=(int)rint(audio_bytesout*8./timebase*.001);
  1723. fprintf(stderr,
  1724. "\r %d:%02d:%02d.%02d audio: %dkbps video: %dkbps ",
  1725. hours,minutes,seconds,hundredths,akbps,vkbps);
  1726. }
  1727. }
  1728. if(video)th_encode_free(td);
  1729. }
  1730. /* clear out state */
  1731. if(audio && twopass!=1){
  1732. ogg_stream_clear(&vo);
  1733. vorbis_block_clear(&vb);
  1734. vorbis_dsp_clear(&vd);
  1735. vorbis_comment_clear(&vc);
  1736. vorbis_info_clear(&vi);
  1737. if(audio!=stdin)fclose(audio);
  1738. }
  1739. if(video){
  1740. ogg_stream_clear(&to);
  1741. th_comment_clear(&tc);
  1742. if(video!=stdin)fclose(video);
  1743. }
  1744. if(outfile && outfile!=stdout)fclose(outfile);
  1745. if(twopass_file)fclose(twopass_file);
  1746. clock_end=clock();
  1747. elapsed=(clock_end-clock_start)/(double)CLOCKS_PER_SEC;
  1748. if(!quiet){
  1749. fprintf(stderr,"\r \n");
  1750. fprintf(stderr," %lld frames in %.3lf seconds: %.3lf Mpixel/s",
  1751. (long long)frames,elapsed,
  1752. (double)1e-6*frames*frame_w*frame_h/elapsed);
  1753. fprintf(stderr," %.2lfx",
  1754. (double)frames*video_fps_d/(elapsed*video_fps_n));
  1755. fprintf(stderr,"\ndone.\n\n");
  1756. }
  1757. return(0);
  1758. }