wrjpgcom.pas 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  1. Program WrJpgCom;
  2. { wrjpgcom.c
  3. Copyright (C) 1994-1997, Thomas G. Lane.
  4. This file is part of the Independent JPEG Group's software.
  5. For conditions of distribution and use, see the accompanying README file.
  6. This file contains a very simple stand-alone application that inserts
  7. user-supplied text as a COM (comment) marker in a JFIF file.
  8. This may be useful as an example of the minimum logic needed to parse
  9. JPEG markers. }
  10. uses
  11. jmorecfg,
  12. jinclude,
  13. cdjpeg,
  14. strings,
  15. fcache;
  16. const
  17. EXIT_FAILURE = 1; { define Halt() codes if not provided }
  18. EXIT_SUCCESS = 0;
  19. { Reduce this value if your malloc() can't allocate blocks up to 64K.
  20. On DOS, compiling in large model is usually a better solution. }
  21. const
  22. MAX_COM_LENGTH = Long(32000); { must be <= 65533 in any case }
  23. { These macros are used to read the input file and write the output file.
  24. To reuse this code in another application, you might need to change these. }
  25. var
  26. infile : file; { input JPEG file }
  27. { Return next input byte, or EOF if no more }
  28. var
  29. outfile : file; { output JPEG file }
  30. { Emit an output byte }
  31. function NEXTBYTE : byte;
  32. var
  33. B : Byte;
  34. begin
  35. BlockRead(Infile,B,1);
  36. NEXTBYTE :=b;
  37. // fc_getc(var fc : Cache);
  38. { Read a byte at the current buffer read-index, increment the buffer
  39. read-index }
  40. end;
  41. procedure PUTBYTE(c : int);
  42. begin
  43. BlockWrite(outfile,c, 1);
  44. end;
  45. { Error exit handler }
  46. procedure ERREXIT(msg : string);
  47. begin
  48. WriteLn(msg);
  49. Halt(EXIT_FAILURE);
  50. end;
  51. { Read one byte, testing for EOF }
  52. function read_1_byte : int;
  53. var
  54. c : byte;
  55. begin
  56. c := NEXTBYTE;
  57. if (c = int(EOF)) then
  58. ERREXIT('Premature EOF in JPEG file');
  59. read_1_byte := c;
  60. end;
  61. { Read 2 bytes, convert to uint }
  62. { All 2-byte quantities in JPEG markers are MSB first }
  63. function read_2_bytes : uint;
  64. var
  65. c1, c2 : int;
  66. begin
  67. c1 := NEXTBYTE;
  68. if (c1 = int(EOF)) then
  69. ERREXIT('Premature EOF in JPEG file');
  70. c2 := NEXTBYTE;
  71. if (c2 = int(EOF)) then
  72. ERREXIT('Premature EOF in JPEG file');
  73. read_2_bytes := ((uint(c1)) shl 8) + (uint(c2));
  74. end;
  75. { Routines to write data to output file }
  76. procedure write_1_byte (c : int);
  77. begin
  78. PUTBYTE(c);
  79. end;
  80. procedure write_2_bytes (val : uint);
  81. begin
  82. PUTBYTE((val shr 8) and $FF);
  83. PUTBYTE(val and $FF);
  84. end;
  85. procedure write_marker (marker : int);
  86. begin
  87. PUTBYTE($FF);
  88. PUTBYTE(marker);
  89. end;
  90. procedure copy_rest_of_file;
  91. var
  92. c : int;
  93. begin
  94. repeat
  95. c := NEXTBYTE;
  96. if (c <> int(EOF)) then
  97. PUTBYTE(c);
  98. until (c = int(EOF));
  99. end;
  100. { JPEG markers consist of one or more $FF bytes, followed by a marker
  101. code byte (which is not an FF). Here are the marker codes of interest
  102. in this program. (See jdmarker.c for a more complete list.) }
  103. const
  104. M_SOF0 = $C0; { Start Of Frame N }
  105. M_SOF1 = $C1; { N indicates which compression process }
  106. M_SOF2 = $C2; { Only SOF0-SOF2 are now in common use }
  107. M_SOF3 = $C3;
  108. M_SOF5 = $C5; { NB: codes C4 and CC are NOT SOF markers }
  109. M_SOF6 = $C6;
  110. M_SOF7 = $C7;
  111. M_SOF9 = $C9;
  112. M_SOF10 = $CA;
  113. M_SOF11 = $CB;
  114. M_SOF13 = $CD;
  115. M_SOF14 = $CE;
  116. M_SOF15 = $CF;
  117. M_SOI = $D8; { Start Of Image (beginning of datastream) }
  118. M_EOI = $D9; { End Of Image (end of datastream) }
  119. M_SOS = $DA; { Start Of Scan (begins compressed data) }
  120. M_COM = $FE; { COMment }
  121. { Find the next JPEG marker and return its marker code.
  122. We expect at least one FF byte, possibly more if the compressor used FFs
  123. to pad the file. (Padding FFs will NOT be replicated in the output file.)
  124. There could also be non-FF garbage between markers. The treatment of such
  125. garbage is unspecified; we choose to skip over it but emit a warning msg.
  126. NB: this routine must not be used after seeing SOS marker, since it will
  127. not deal correctly with FF/00 sequences in the compressed image data... }
  128. function next_marker : int;
  129. var
  130. c : int;
  131. discarded_bytes : int;
  132. begin
  133. discarded_bytes := 0;
  134. { Find $FF byte; count and skip any non-FFs. }
  135. c := read_1_byte;
  136. while (c <> $FF) do
  137. begin
  138. Inc(discarded_bytes);
  139. c := read_1_byte;
  140. end;
  141. { Get marker code byte, swallowing any duplicate FF bytes. Extra FFs
  142. are legal as pad bytes, so don't count them in discarded_bytes. }
  143. repeat
  144. c := read_1_byte;
  145. until (c <> $FF);
  146. if (discarded_bytes <> 0) then
  147. begin
  148. WriteLn('Warning: garbage data found in JPEG file');
  149. end;
  150. next_marker := c;
  151. end;
  152. { Read the initial marker, which should be SOI.
  153. For a JFIF file, the first two bytes of the file should be literally
  154. $FF M_SOI. To be more general, we could use next_marker, but if the
  155. input file weren't actually JPEG at all, next_marker might read the whole
  156. file and then return a misleading error message... }
  157. function first_marker : int;
  158. var
  159. c1, c2 : int;
  160. begin
  161. c1 := NEXTBYTE;
  162. c2 := NEXTBYTE;
  163. if (c1 <> $FF) or (c2 <> M_SOI) then
  164. ERREXIT('Not a JPEG file');
  165. first_marker := c2;
  166. end;
  167. { Most types of marker are followed by a variable-length parameter segment.
  168. This routine skips over the parameters for any marker we don't otherwise
  169. want to process.
  170. Note that we MUST skip the parameter segment explicitly in order not to
  171. be fooled by $FF bytes that might appear within the parameter segment;
  172. such bytes do NOT introduce new markers. }
  173. procedure copy_variable;
  174. { Copy an unknown or uninteresting variable-length marker }
  175. var
  176. length : uint;
  177. begin
  178. { Get the marker parameter length count }
  179. length := read_2_bytes;
  180. write_2_bytes(length);
  181. { Length includes itself, so must be at least 2 }
  182. if (length < 2) then
  183. ERREXIT('Erroneous JPEG marker length');
  184. Dec(length, 2);
  185. { Skip over the remaining bytes }
  186. while (length > 0) do
  187. begin
  188. write_1_byte(read_1_byte);
  189. Dec(length);
  190. end;
  191. end;
  192. procedure skip_variable;
  193. { Skip over an unknown or uninteresting variable-length marker }
  194. var
  195. length : uint;
  196. begin
  197. { Get the marker parameter length count }
  198. length := read_2_bytes;
  199. { Length includes itself, so must be at least 2 }
  200. if (length < 2) then
  201. ERREXIT('Erroneous JPEG marker length');
  202. Dec(length, 2);
  203. { Skip over the remaining bytes }
  204. while (length > 0) do
  205. begin
  206. read_1_byte;
  207. Dec(length);
  208. end;
  209. end;
  210. { Parse the marker stream until SOFn or EOI is seen;
  211. copy data to output, but discard COM markers unless keep_COM is true. }
  212. function scan_JPEG_header (keep_COM : boolean) : int;
  213. var
  214. marker : int;
  215. begin
  216. { Expect SOI at start of file }
  217. if (first_marker <> M_SOI) then
  218. ERREXIT('Expected SOI marker first');
  219. write_marker(M_SOI);
  220. { Scan miscellaneous markers until we reach SOFn. }
  221. while TRUE do
  222. begin
  223. marker := next_marker;
  224. case marker of
  225. { Note that marker codes $C4, $C8, $CC are not, and must not be,
  226. treated as SOFn. C4 in particular is actually DHT. }
  227. M_SOF0, { Baseline }
  228. M_SOF1, { Extended sequential, Huffman }
  229. M_SOF2, { Progressive, Huffman }
  230. M_SOF3, { Lossless, Huffman }
  231. M_SOF5, { Differential sequential, Huffman }
  232. M_SOF6, { Differential progressive, Huffman }
  233. M_SOF7, { Differential lossless, Huffman }
  234. M_SOF9, { Extended sequential, arithmetic }
  235. M_SOF10, { Progressive, arithmetic }
  236. M_SOF11, { Lossless, arithmetic }
  237. M_SOF13, { Differential sequential, arithmetic }
  238. M_SOF14, { Differential progressive, arithmetic }
  239. M_SOF15: { Differential lossless, arithmetic }
  240. begin
  241. scan_JPEG_header := marker;
  242. exit;
  243. end;
  244. M_SOS: { should not see compressed data before SOF }
  245. ERREXIT('SOS without prior SOFn');
  246. M_EOI: { in case it's a tables-only JPEG stream }
  247. begin
  248. scan_JPEG_header := marker;
  249. exit;
  250. end;
  251. M_COM: { Existing COM: conditionally discard }
  252. if (keep_COM) then
  253. begin
  254. write_marker(marker);
  255. copy_variable;
  256. end
  257. else
  258. begin
  259. skip_variable;
  260. end;
  261. else { Anything else just gets copied }
  262. write_marker(marker);
  263. copy_variable; { we assume it has a parameter count... }
  264. end;
  265. end; { end loop }
  266. end;
  267. { Command line parsing code }
  268. var
  269. progname : string; { program name for error messages }
  270. procedure usage;
  271. { complain about bad command line }
  272. begin
  273. WriteLn('wrjpgcom inserts a textual comment in a JPEG file.');
  274. WriteLn('You can add to or replace any existing comment(s).');
  275. Write('Usage: ',progname,' [switches] ');
  276. {$ifdef TWO_FILE_COMMANDLINE
  277. WriteLn('inputfile outputfile');
  278. {$else}
  279. WriteLn('[inputfile]');
  280. {$endif}
  281. WriteLn('Switches (names may be abbreviated):');
  282. WriteLn(' -replace Delete any existing comments');
  283. WriteLn(' -comment "text" Insert comment with given text');
  284. WriteLn(' -cfile name Read comment from named file');
  285. WriteLn('Notice that you must put quotes around the comment text');
  286. WriteLn('when you use -comment.');
  287. WriteLn('If you do not give either -comment or -cfile on the command line,');
  288. WriteLn('then the comment text is read from standard input.');
  289. WriteLn('It can be multiple lines, up to ',
  290. uint(MAX_COM_LENGTH),' characters total.');
  291. {$ifndef TWO_FILE_COMMANDLINE}
  292. WriteLn('You must specify an input JPEG file name when supplying');
  293. WriteLn('comment text from standard input.');
  294. {$endif}
  295. Halt(EXIT_FAILURE);
  296. end;
  297. function keymatch (const arg : string;
  298. const keyword : string;
  299. minchars : int) : boolean;
  300. { Case-insensitive matching of (possibly abbreviated) keyword switches. }
  301. { keyword is the constant keyword (must be lower case already), }
  302. { minchars is length of minimum legal abbreviation. }
  303. var
  304. {register} ca, ck : char;
  305. {register} nmatched : int;
  306. i, len : int;
  307. begin
  308. nmatched := 0;
  309. keymatch := FALSE;
  310. len := Length(keyword);
  311. if len >= Length(arg) then
  312. len := Length(arg)
  313. else
  314. exit;
  315. for i := 1 to len do
  316. begin
  317. if (UpCase(arg[i]) <> UpCase(keyword[i])) then
  318. exit;
  319. Inc(nmatched); { count matched characters }
  320. end;
  321. { reached end of argument; fail if it's too short for unique abbrev }
  322. if (nmatched >= minchars) then
  323. keymatch := TRUE; { A-OK }
  324. end;
  325. { The main program. }
  326. var
  327. argc,
  328. argn : int;
  329. arg : string;
  330. keep_COM : boolean;
  331. comment_arg : string;
  332. comment_arg_0 : PChar;
  333. comment_file : TBufStream;
  334. comment_length : uint;
  335. marker : int;
  336. var
  337. src_file : PBufStream;
  338. c : int;
  339. begin
  340. keep_COM := TRUE;
  341. comment_arg := '';
  342. comment_length := 0;
  343. { On Mac, fetch a command line. }
  344. argc := ParamCount;
  345. progname := ParamStr(0);
  346. { Parse switches, if any }
  347. argn := 1;
  348. while (argn < argc) do
  349. begin
  350. arg := ParamStr(argn);
  351. if (arg[1] <> '-') then
  352. break; { not switch, must be file name }
  353. if (keymatch(arg, '-replace', 2)) then
  354. begin
  355. keep_COM := FALSE;
  356. end
  357. else
  358. if (keymatch(arg, '-cfile', 3)) then
  359. begin
  360. Inc(argn);
  361. if (argn >= argc) then
  362. usage;
  363. if not comment_file.Init(ParamStr(argn), stOpenRead, 2048) then
  364. begin
  365. WriteLn(progname, 'can''t open ', ParamStr(argn));
  366. Halt(EXIT_FAILURE);
  367. end;
  368. end
  369. else
  370. {$ifdef comment}
  371. if (keymatch(arg, '-comment', 2)) then
  372. begin
  373. Inc(argn);
  374. if (argn >= argc) then
  375. usage;
  376. comment_arg := ParamStr(argn);
  377. { If the comment text starts with '"', then we are probably running
  378. under MS-DOG and must parse out the quoted string ourselves. Sigh. }
  379. if (comment_arg[1] = '"') then
  380. begin
  381. GetMem(comment_arg_0, size_t(MAX_COM_LENGTH) );
  382. if (comment_arg_0 = NIL) then
  383. ERREXIT('Insufficient memory');
  384. strcopy(comment_arg_0, ParamStr(argn)+1);
  385. while TRUE do
  386. begin
  387. comment_length := uint( strlen(comment_arg) );
  388. if (comment_length > 0) and
  389. (comment_arg[comment_length-1] = '"') then
  390. begin
  391. comment_arg[comment_length-1] := #0; { zap terminating quote }
  392. break;
  393. end;
  394. Inc(argn);
  395. if (argn >= argc) then
  396. ERREXIT('Missing ending quote mark');
  397. strcat(comment_arg, ' ');
  398. strcat(comment_arg, argv[argn]);
  399. end;
  400. end;
  401. comment_length := uint(strlen(comment_arg));
  402. end
  403. else
  404. usage;
  405. {$endif}
  406. Inc(argn);
  407. end;
  408. { Cannot use both -comment and -cfile. }
  409. if (comment_arg <> '') and (comment_file.status <> stOK) then
  410. usage;
  411. { If there is neither -comment nor -cfile, we will read the comment text
  412. from stdin; in this case there MUST be an input JPEG file name. }
  413. if (comment_arg = '') and (comment_file.status <> stOK) and (argn >= argc) then
  414. usage;
  415. { Open the input file. }
  416. if (argn < argc) then
  417. begin
  418. infile.Init(ParamStr(argn), stOpenRead, 2048);
  419. if (infile.Status <> stOK) then
  420. begin
  421. WriteLn(progname, ': can''t open ', ParamStr(argn));
  422. Halt(EXIT_FAILURE);
  423. end;
  424. end
  425. else
  426. begin
  427. { default input file is stdin }
  428. {$ifdef USE_FDOPEN} { need to re-open in binary mode? }
  429. infile := TBufStream.Init('', stOpenRead, 2048);
  430. if (infile.Status <> stOK) then
  431. begin
  432. WriteLn(progname, ': can''t open stdin');
  433. Halt(EXIT_FAILURE);
  434. end;
  435. {$else}
  436. {infile := input;}
  437. RunError(255);
  438. {$endif}
  439. end;
  440. { Open the output file. }
  441. {$ifdef TWO_FILE_COMMANDLINE}
  442. { Must have explicit output file name }
  443. if (argn <> argc-2) then
  444. begin
  445. WriteLn(progname, ': must name one input and one output file');
  446. usage;
  447. end;
  448. outfile := TBufStream.Init(ParamStr(argn+1), stOpenWrite, 2048);
  449. if (outfile.Status <> stOK) then
  450. begin
  451. WriteLn(progname, ': can't open ', ParamStr(argn+1));
  452. Halt(EXIT_FAILURE);
  453. end;
  454. {$else}
  455. { Unix style: expect zero or one file name }
  456. if (argn < argc-1) then
  457. begin
  458. WriteLn(progname, ': only one input file');
  459. usage;
  460. end;
  461. { default output file is stdout }
  462. {$ifdef USE_FDOPEN} { need to re-open in binary mode? }
  463. outfile := TBufStream.Init('', stOpenWrite, 2048);
  464. if (outfile.Status <> stOK) then
  465. begin
  466. WriteLn(progname, ': can''t open stdout');
  467. Halt(EXIT_FAILURE);
  468. end;
  469. {$else}
  470. RunError(255);
  471. {outfile := stdout;}
  472. {$endif}
  473. {$endif} { TWO_FILE_COMMANDLINE }
  474. { Collect comment text from comment_file or stdin, if necessary }
  475. if (comment_arg_0 = NIL) then
  476. begin
  477. GetMem(comment_arg_0, size_t(MAX_COM_LENGTH) );
  478. if (comment_arg_0 = NIL) then
  479. ERREXIT('Insufficient memory');
  480. comment_length := 0;
  481. if comment_file.status = stOK then
  482. src_file := @comment_file
  483. else
  484. src_file := NIL;
  485. repeat
  486. c := getc(src_file);
  487. if (c <> EOF) do
  488. begin
  489. if (comment_length >= uint(MAX_COM_LENGTH)) then
  490. begin
  491. WriteLn('Comment text may not exceed ',
  492. uint(MAX_COM_LENGTH)),' bytes);
  493. Halt(EXIT_FAILURE);
  494. end;
  495. comment_arg[comment_length] := char(c);
  496. Inc(comment_length);
  497. end;
  498. until (c = EOF);
  499. if (comment_file <> '') then
  500. fclose(comment_file);
  501. end;
  502. { Copy JPEG headers until SOFn marker;
  503. we will insert the new comment marker just before SOFn.
  504. This (a) causes the new comment to appear after, rather than before,
  505. existing comments; and (b) ensures that comments come after any JFIF
  506. or JFXX markers, as required by the JFIF specification. }
  507. marker := scan_JPEG_header(keep_COM);
  508. { Insert the new COM marker, but only if nonempty text has been supplied }
  509. if (comment_length > 0) then
  510. begin
  511. write_marker(M_COM);
  512. write_2_bytes(comment_length + 2);
  513. while (comment_length > 0) do
  514. begin
  515. write_1_byte(comment_arg^);
  516. Inc(comment_arg);
  517. Dec(comment_length);
  518. end;
  519. end;
  520. { Duplicate the remainder of the source file.
  521. Note that any COM markers occuring after SOF will not be touched. }
  522. write_marker(marker);
  523. copy_rest_of_file();
  524. { All done. }
  525. Halt(EXIT_SUCCESS);
  526. end.