]> git.datanom.net - lensdb.git/blob - lib/exiftool/ExifTool.cpp
fix spelling error. add more precise maker finder
[lensdb.git] / lib / exiftool / ExifTool.cpp
1 //------------------------------------------------------------------------------
2 // File: ExifTool.cpp
3 //
4 // Description: C++ library interface to Perl exiftool application script
5 //
6 // License: Copyright 2013-2019, Phil Harvey (philharvey66 at gmail.com)
7 //
8 // This is software, in whole or part, is free for use in
9 // non-commercial applications, provided that this copyright notice
10 // is retained. A licensing fee may be required for use in a
11 // commercial application.
12 //
13 // Created: 2013-11-23 - Phil Harvey
14 //------------------------------------------------------------------------------
15
16 #include <stdio.h>
17 #include <stdlib.h>
18 #include <string.h>
19 #include <unistd.h>
20 #include <signal.h>
21 #include <fcntl.h>
22 #include <errno.h>
23 #include <ctype.h>
24 #include <sys/time.h>
25 #include <sys/wait.h>
26 #include "ExifTool.h"
27
28 const int kOutBlockSize = 65536; // size increment for exiftool stdout buffer
29 const int kErrBlockSize = 4096; // size increment for exiftool stderr buffer
30 const int kCmdBlockSize = 8192; // size increment for exiftool command buffer
31
32 const char *kDefaultExec = "exiftool";
33
34 static int sBrokenPipe = -1;
35
36 int ExifTool::sNoSigPipe = 0;
37 int ExifTool::sNoWatchdog = 0;
38
39 //------------------------------------------------------------------------------
40 // SIGPIPE handler
41 static void sigPipeAction(int sig)
42 {
43 sBrokenPipe = 1;
44 }
45
46 //------------------------------------------------------------------------------
47 // Unescape C-style escape sequences in a null-terminated string
48 // (as found in values of exiftool -php output)
49 // Returns: number of bytes in unescaped data (including null terminator)
50 // - on return string contains binary data which may have embedded zero bytes
51 static int unescape(char *str)
52 {
53 char *src = strchr(str, '\\');
54 // return string length without converting if string doesn't contain escapes
55 if (!src) return((int)(strlen(str) + 1));
56 char *dst = src;
57 for (;;) {
58 char ch = *(src++);
59 if (ch == '\\') {
60 // must un-escape this character
61 ch = *(src++);
62 switch (ch) {
63 case 'x':
64 // decode 2-digit hex character
65 ch = 0;
66 for (int i=0; i<2; ++i) {
67 char nibble = *(src++);
68 if (nibble >= '0' && nibble <= '9') {
69 nibble -= '0';
70 } else if (nibble >= 'A' && nibble <= 'F') {
71 nibble -= 'A' - 10;
72 } else if (nibble >= 'a' && nibble <= 'f') {
73 nibble -= 'a' - 10;
74 } else {
75 ch = 0; // (shouldn't happen)
76 break;
77 }
78 ch = (ch << 4) + nibble;
79 }
80 break;
81 case 't':
82 ch = '\t';
83 break;
84 case 'n':
85 ch = '\n';
86 break;
87 case 'r':
88 ch = '\r';
89 break;
90 case '\0': // (shouldn't happen, but just to be safe)
91 *(dst++) = ch;
92 return((int)(dst - str));
93 default:
94 // pass any other character straight through
95 break;
96 }
97 *(dst++) = ch;
98 } else {
99 *(dst++) = ch;
100 if (!ch) break;
101 }
102 }
103 return((int)(dst - str));
104 }
105
106 //------------------------------------------------------------------------------
107 // get current hi-resolution time
108 static double getTime()
109 {
110 struct timeval tv;
111 struct timezone tz;
112 gettimeofday(&tv,&tz);
113 return(tv.tv_sec + 1e-6 * tv.tv_usec);
114 }
115
116 //==============================================================================
117 // ExifTool object constructor
118 //------------------------------------------------------------------------------
119 // Inputs: exec - path name to executable file (ie. "perl" or "exiftool")
120 // arg1 - optional first argument (ie. "exiftool" if exec="perl")
121 ExifTool::ExifTool(const char *exec, const char *arg1)
122 : mWatchdog(-1), mWriteInfo(NULL), mCmdQueue(NULL), mCmdQueueLen(0),
123 mCmdQueueSize(0), mLastComplete(0), mCmdNum(0), mWaitTime(1000)
124 {
125 int to[2], from[2], err[2];
126 const char *args[7];
127 args[0] = NULL;
128 args[1] = kDefaultExec;
129 args[2] = "-stay_open";
130 args[3] = "true";
131 args[4] = "-@";
132 args[5] = "-";
133 args[6] = NULL;
134
135 int firstArg = 1;
136 if (arg1) {
137 args[1] = arg1;
138 --firstArg;
139 }
140 args[firstArg] = exec ? exec : kDefaultExec;
141
142 // set up handler for SIGPIPE if not done already
143 if (sBrokenPipe == -1 && !sNoSigPipe) {
144 struct sigaction act1;
145 sigemptyset(&act1.sa_mask);
146 act1.sa_flags = SA_SIGINFO;
147 act1.sa_handler = sigPipeAction;
148 if (sigaction(SIGPIPE, &act1, (struct sigaction *)NULL) < 0) {
149 sBrokenPipe = -2; // error!
150 } else {
151 sBrokenPipe = 0;
152 }
153 }
154
155 // create our pipes
156 pipe(to);
157 pipe(from);
158 pipe(err);
159
160 // fork and exec exiftool
161 mPid = fork();
162
163 if (mPid == 0) {
164 // this is our exiftool thread
165 close(to[1]);
166 close(from[0]);
167 close(err[0]);
168 dup2(to[0], STDIN_FILENO);
169 dup2(from[1], STDOUT_FILENO);
170 dup2(err[1], STDERR_FILENO);
171 close(to[0]);
172 close(from[1]);
173 close(err[1]);
174 execvp(args[firstArg], (char * const *)args + firstArg);
175 // (if execvp succeeds, it will never return)
176 exit(0);
177 } else {
178 // this is our working thread
179 close(to[0]);
180 close(from[1]);
181 close(err[1]);
182 // allocate memory for exiftool response and error messages
183 mStdout.Init(from[0], mPid, kOutBlockSize);
184 mStderr.Init(err[0], mPid, kErrBlockSize);
185 mTo = to[1];
186 // set output exiftool argument pipe to non-blocking
187 int flags = fcntl(mTo, F_GETFL, 0);
188 fcntl(mTo, F_SETFL, flags | O_NONBLOCK);
189 // create a watchdog process to monitor the main program thread and
190 // terminate the exiftool process if necessary when the program exits
191 // (otherwise exiftool processes may be left running if an ExifTool
192 // object wasn't properly deleted)
193 if (mPid != -1 && !sNoWatchdog) {
194 int pid = getpid(); // pid of this process
195 mWatchdog = fork();
196 if (!mWatchdog) {
197 // monitor the main program and clean up if it dies
198 // (under normal conditions this watchdog process
199 // is killed in the destructor)
200 for (;;) {
201 sleep(1);
202 // if the main thread dies, our parent PID will change
203 if (getppid() == pid) continue;
204 // our parent has died, so send a SIGINT to exiftool
205 kill(mPid, SIGINT);
206 exit(0); // exit the watchdog process
207 }
208 }
209 }
210 }
211 }
212
213 //------------------------------------------------------------------------------
214 // Terminate exiftool application process and close files
215 ExifTool::~ExifTool()
216 {
217 delete mWriteInfo;
218 delete [] mCmdQueue;
219 mCmdQueue = NULL;
220 Command("-stay_open\nfalse\n");
221 close(mTo);
222 // wait for the exiftool process to terminate
223 while (IsRunning()) {
224 // keep reading exiftool output so the process won't be blocked,
225 // and wait until all commands complete unless we get an error
226 if (Complete() < 0) {
227 kill(mPid, SIGINT); // pull the plug
228 waitpid(mPid, NULL, 0); // avoid zombie process
229 break;
230 }
231 usleep(100); // relax
232 }
233 if (mWatchdog > 0) {
234 kill(mWatchdog, SIGINT); // kill our watchdog process
235 waitpid(mWatchdog, NULL, 0);// avoid zombie
236 }
237 }
238
239 //------------------------------------------------------------------------------
240 // Extract metadata from specified image
241 // Inputs: file - source file name
242 // opts - string of exiftool options, separated by newlines
243 // timeout - maximum wait time (floating point seconds)
244 // Returns: linked list of tag information structures for extracted information
245 // - valid options: "-b\n" - extract binary data (other options may mess up TagInfo parsing)
246 // - waits for exiftool command to complete, then parses returned messages
247 // to generate the TagInfo list
248 // - caller is responsible for deleting returned TagInfo ("delete info;")
249 TagInfo * ExifTool::ImageInfo(const char *file, const char *opts, double timeout)
250 {
251 int cmdNum = ExtractInfo(file, opts);
252
253 // error unless command number is > 0
254 if (cmdNum <= 0) return (TagInfo *)NULL;
255
256 return GetInfo(cmdNum, timeout);
257 }
258
259 //------------------------------------------------------------------------------
260 // Send command to extract information from one or more files
261 // Inputs: file - source file name(s)
262 // opts - exiftool options, separated by newlines
263 // Returns: command number (>0), or error (<0)
264 int ExifTool::ExtractInfo(const char *file, const char *opts)
265 {
266 if (!file) return -5;
267
268 // prepare command arguments for exiftool
269 int flen = (int)strlen(file);
270 int olen = opts ? (int)strlen(opts) : 0;
271
272 char *buff = new char[flen + olen + 64];
273 if (!buff) return -3; // out of memory!
274 memcpy(buff, file, flen);
275
276 // extract information using exiftool -php option
277 // (also add "-l -G:0:1:2:4 -D" to get more details for TagInfo structure)
278 strcpy(buff + flen, "\n-php\n-l\n-G:0:1:2:4\n-D\n-sep\n, \n");
279
280 // add extra options specified by the caller
281 if (opts) {
282 strcat(buff, opts);
283 strcat(buff, "\n"); // (to be safe; blank lines are ignored)
284 }
285
286 // send the command to exiftool
287 int cmdNum = Command(buff);
288 delete [] buff;
289
290 return cmdNum;
291 }
292
293 //------------------------------------------------------------------------------
294 // Read exiftool output and convert to list of TagInfo structures
295 // Inputs: cmdNum - command number (0 to process next output in series,
296 // or -1 to process previously completed command)
297 // timeout - maximum wait time (floating point seconds)
298 // Returns: linked list of tag information structures for extracted information
299 // - waits up to timeout time for exiftool command to complete
300 // - caller is responsible for deleting returned TagInfo ("delete info;")
301 // - after return, GetError() may be called to get exiftool errors
302 TagInfo *ExifTool::GetInfo(int cmdNum, double timeout)
303 {
304 TagInfo *info = (TagInfo *)NULL;
305 TagInfo *next = (TagInfo *)NULL;
306 TagInfo *infoList = (TagInfo *)NULL;
307
308 // wait for specified command to complete
309 if (cmdNum >= 0) {
310 for (;;) {
311 int n = Complete(timeout);
312 if (n <= 0) return info;
313 if (n == cmdNum || !cmdNum) break;
314 }
315 } else if (mLastComplete <= 0) {
316 return info;
317 }
318
319 // parse the response string, line by line
320 char *pt = mStdout.GetString();
321 if (!pt) return info;
322
323 int mode = 0; // 0=looking for tag name, 1=tag properties
324
325 for (;;) {
326 // find the end of this line
327 char *p0 = pt;
328 pt = strchr(pt, '\n');
329 if (!pt) break;
330 *pt = '\0'; // null terminate this line
331 ++pt; // continue at next line
332 // scan for opening quote
333 p0 = strchr(p0, '"');
334 if (!p0) {
335 // no quote on line, so this must be the end of the tag info,
336 // so fill in necessary members of this TagInfo structure
337 if (info) {
338 // (name and value are guaranteed to exist)
339 if (!info->value) {
340 info->value = new char[1];
341 if (!info->value) break;
342 info->value[0] = '\0';
343 }
344 if (!info->num) {
345 info->num = info->value;
346 info->numLen = info->valueLen;
347 }
348 }
349 mode = 0; // look for next tag name
350 continue;
351 }
352 char *p1 = ++p0;
353 if (!mode) { // looking for new tag
354 if (next) delete next; // delete old unused structure if necessary
355 // create new TagInfo structure for this tag
356 next = new TagInfo;
357 if (!next) break;
358 // extract tag/group names
359 int g = 0;
360 for (;;) {
361 char ch = *p1;
362 if (ch == '"' || ch == ':') {
363 int n = (int)(p1 - p0);
364 char *str = new char[n + 1];
365 if (!str) break;
366 memcpy(str, p0, n);
367 str[n] = '\0';
368 if (ch == '"') {
369 next->name = str; // save tag name
370 break;
371 }
372 if (g > 2) {
373 // get copy number
374 if (!memcmp(str, "Copy", 4)) {
375 next->copyNum = atoi(str+4);
376 delete [] str; // done with this string
377 }
378 } else {
379 next->group[g] = str; // save group name
380 }
381 ++g;
382 p0 = p1 + 1;
383 }
384 ++p1;
385 }
386 if (!next->name) continue;
387 // file name given by line like: "SourceFile" => "images/a.jpg",
388 if (!strcmp(next->name,"SourceFile")) {
389 char *p2 = pt - 2;
390 if (*p2 == '\r') --p2; // skip Windows CR
391 if (*p2 == ',') --p2;
392 if (*p2 != '"') continue;
393 int n = (int)(p2 - p1 - 6);
394 if (n < 0) continue;
395 char *str = new char[n+1];
396 if (!str) break;
397 memcpy(str, p1+6, n);
398 str[n] = '\0';
399 next->value = next->num = str;
400 next->valueLen = next->numLen = n;
401 } else {
402 mode = 1; // read tag properties next
403 }
404 // add to linked list of information
405 if (info) {
406 info->next = next;
407 } else {
408 infoList = next;
409 }
410 info = next;
411 next = NULL;
412 } else {
413 // isolate the property name
414 p1 = strchr(p0, '"');
415 if (!p1) break; // (shouldn't happen)
416 *p1 = '\0'; // null terminate property name
417 p1 += 5; // step to start of value
418 if (p1 >= pt) break; // (shouldn't happen);
419 if (*p1 == '"') ++p1; // skip quote if it exists
420 char *p2 = pt - 1;
421 if (p2[-1] == '\r') --p2;// skip Windows CR
422 if (p2[-1] == ',') --p2;// skip trailing comma
423 if (p2[-1] == '"') --p2;// skip trailing quote
424 if (p2 < p1) break; // (shouldn't happen)
425 *p2 = '\0'; // null terminate property value
426 int n = unescape(p1); // unescape characters in property value
427 char **dst;
428 if (!strcmp(p0, "desc")) {
429 dst = &info->desc;
430 } else if (!strcmp(p0, "id")) {
431 dst = &info->id;
432 } else if (!strcmp(p0, "num")) {
433 dst = &info->num;
434 info->numLen = n - 1; // save length too (could be binary data)
435 } else if (!strcmp(p0, "val")) {
436 dst = &info->value;
437 info->valueLen = n - 1; // save length too (could be binary data)
438 } else {
439 continue; // (shouldn't happen)
440 }
441 *dst = new char[n];
442 if (!*dst) break;
443 memcpy(*dst, p1, n); // copy property value
444 }
445 }
446 if (next) delete next;
447 return infoList;
448 }
449
450 //------------------------------------------------------------------------------
451 // Set the new value for a tag
452 // Inputs: tag = tag name (may contain leading group names and trailing '#')
453 // value = tag value data
454 // len = length of value in bytes (defaults to strlen(value))
455 // Returns: number of tags set, or <0 on memory error
456 // - must call WriteInfo() at some point after this to actually write the new values
457 // - call with tag=NULL to reset previous new values
458 // - call with value=NULL to delete tag
459 int ExifTool::SetNewValue(const char *tag, const char *value, int len)
460 {
461 int numSet = 0;
462 if (tag) {
463 TagInfo *info = new TagInfo;
464 if (!info) return -3;
465 info->name = new char[strlen(tag) + 1];
466 if (!info->name) { delete info; return -3; }
467 strcpy(info->name, tag);
468 if (value) {
469 if (len < 0) {
470 if (value) len = (int)strlen(value);
471 else len = 0;
472 }
473 if (len) {
474 info->value = new char[len+1];
475 if (!info->value) { delete info; return -3; }
476 memcpy(info->value, value, len);
477 // add null terminator (but note that we don't use it)
478 info->value[len] = '\0';
479 info->valueLen = len;
480 }
481 }
482 // place at the end of the linked list
483 TagInfo **pt = &mWriteInfo;
484 while (*pt) {
485 ++numSet;
486 pt = &((*pt)->next);
487 }
488 *pt = info;
489 ++numSet;
490 } else {
491 delete mWriteInfo;
492 mWriteInfo = NULL;
493 }
494 return numSet;
495 }
496
497 //------------------------------------------------------------------------------
498 // Write metadata to specified image
499 // Inputs: file - one or more directory and/or file names, separated by newlines
500 // opts - extra exiftool options, separated by newlines
501 // info - pointer to linked list of tags to write (overrides SetNewValue() calls)
502 // Returns: >0 command number, <0=error
503 // - each option argument must be terminated with a newline
504 // - file may be one or more file names separated by newlines
505 // - must call Complete() after this to check the return messages
506 // - ignores "SourceFile" entries in input TagInfo list
507 int ExifTool::WriteInfo(const char *file, const char *opts, TagInfo *info)
508 {
509 if (!file) return -5;
510
511 const int kBlockSize = 65536;
512 char *buff = new char[kBlockSize];
513 if (!buff) return -3;
514 // get length of all options (plus 12 extra characters for "-ex\n-sep\n, \n")
515 int olen = (int)((opts ? strlen(opts)+1 : 0) + 12);
516 int size = kBlockSize;
517 strcpy(buff, file);
518 int pos = (int)strlen(file);
519 buff[pos++] = '\n';
520 int escaped = 0;
521
522 // use internal new value list if not specified
523 if (!info) info = mWriteInfo;
524
525 // prepare assignment arguments for exiftool, looping through all tags to write
526 while (info) {
527 if (!info->name || strlen(info->name) > 100 || !strcmp(info->name, "SourceFile")) {
528 info = info->next;
529 continue;
530 }
531 // construct the tag name
532 char tag[1024];
533 tag[0] = '\0';
534 for (int i=0; i<3; ++i) {
535 if (info->group[i] && strlen(info->group[i]) < 100) {
536 char *pt = strchr(tag, '\0');
537 *(pt++) = '0' + i; // leading family number
538 strcpy(pt, info->group[i]); // group name
539 strcat(tag,":"); // colon separator
540 }
541 }
542 strcat(tag, info->name);
543 // which value are we writing (converted or numerical?)
544 char *val = info->value;
545 int valLen = info->valueLen;
546 if (!val) {
547 val = info->num;
548 valLen = info->numLen;
549 if (val) strcat(tag, "#"); // write numerical value
550 }
551 int tagLen = (int)strlen(tag);
552 int origLen = valLen;
553 // count the number of characters in the value that need escaping
554 if (val) {
555 char *pt = val;
556 char *end = pt + origLen;
557 int count = 0;
558 while (pt < end) {
559 char ch = *(pt++);
560 if (ch==10 || ch=='&' || ch=='\0') ++count;
561 }
562 valLen += count * 4; // 4 extra bytes for each escaped character
563 }
564 // prepare exiftool argument (format is: "-TAG=VALUE\n")
565 int n = tagLen + valLen + 3;
566 // expand buffer if necessary
567 if (pos + n + olen > size) {
568 size += n + kBlockSize;
569 char *buf2 = new char[size];
570 if (!buf2) { delete [] buff; return -3; }
571 memcpy(buf2, buff, pos);
572 delete [] buff;
573 buff = buf2;
574 }
575 buff[pos++] = '-';
576 memcpy(buff+pos, tag, tagLen);
577 pos += tagLen;
578 buff[pos++] = '=';
579 if (valLen == origLen) {
580 if (val) {
581 memcpy(buff+pos, val, valLen);
582 pos += valLen;
583 }
584 } else {
585 // escape newlines and '&' characters in the value
586 char *pt = val;
587 char *end = pt + origLen;
588 char *dst = buff + pos;
589 while (pt < end) {
590 char ch = *(pt++);
591 if (ch == 10) {
592 memcpy(dst, "&#10;", 5);
593 dst += 5;
594 } else if (ch == 0) {
595 memcpy(dst, "&#00;", 5);
596 dst += 5;
597 } else if (ch == '&') {
598 memcpy(dst, "&amp;", 5);
599 dst += 5;
600 } else {
601 *(dst++) = ch;
602 }
603 }
604 pos = (int)(dst - buff);
605 escaped = 1;
606 }
607 buff[pos++] = '\n';
608 info = info->next;
609 }
610 // get exiftool to unescape our newlines if necessary
611 if (escaped) { strcpy(buff+pos, "-ex\n"); pos += 4; }
612 // split concatenated lists back into individual items
613 strcpy(buff+pos, "-sep\n, \n"); pos += 8;
614 // add user-defined options last
615 if (opts) {
616 strcpy(buff+pos, opts);
617 pos += strlen(opts);
618 buff[pos++] = '\n'; // (just in case)
619 buff[pos] = '\0';
620 }
621 int cmdNum = Command(buff);
622 delete [] buff;
623 return cmdNum;
624 }
625
626 //------------------------------------------------------------------------------
627 // Send command to exiftool
628 // Inputs: cmd - exiftool command arguments (separated by newlines)
629 // Returns: command number (1-99999), error (<0),
630 // or 0 if cmd is NULL and the queue is empty
631 // - set cmd to NULL to continue writing previously queued commands
632 // - this routine always returns immediately, and queues command if it couldn't send
633 int ExifTool::Command(const char *cmd)
634 {
635 int n;
636 // check to make sure our exiftool process is still running
637 if (!IsRunning()) return -1;
638 // must first try to send previously queued command
639 if (mCmdQueue) {
640 n = (int)write(mTo, mCmdQueue, mCmdQueueLen);
641 if (n < 0) {
642 if (errno != EAGAIN) return -2; // write error!
643 n = 0;
644 }
645 if (n == mCmdQueueLen) {
646 delete [] mCmdQueue;
647 mCmdQueue = NULL;
648 mCmdQueueSize = 0;
649 } else if (n != 0) {
650 memmove(mCmdQueue, mCmdQueue+n, mCmdQueueLen-n);
651 }
652 mCmdQueueLen -= n;
653 }
654 if (cmd) {
655 // increment to next command number
656 int cmdNum = mCmdNum + 1;
657 if (cmdNum > 99999) cmdNum = 1;
658
659 // compose full command string (cmd2)
660 char buf2[64];
661 int len = (int)strlen(cmd);
662 int len2 = sprintf(buf2, "\n-echo4\n{ready%.5d}\n-execute%.5d\n", cmdNum, cmdNum);
663 char *cmd2 = new char[len + len2];
664 if (!cmd2) return -3; // out of memory!
665 memcpy(cmd2, cmd, len);
666 memcpy(cmd2+len, buf2, len2);
667 len2 += len; // len2 is now the length of the complete command
668
669 // add command to the queue if not empty
670 if (mCmdQueue) {
671 if (mCmdQueueLen + len2 > mCmdQueueSize) {
672 // enlarge queue and add new command
673 int newSize = mCmdQueueLen + len2 + kCmdBlockSize;
674 char *queue = new char[newSize];
675 if (!queue) return -3; // out of memory!
676 memcpy(queue, mCmdQueue, mCmdQueueLen);
677 delete [] mCmdQueue;
678 mCmdQueue = queue;
679 mCmdQueueSize = newSize;
680 }
681 // copy this command into the queue
682 memcpy(mCmdQueue+mCmdQueueLen, cmd2, len2);
683 mCmdQueueLen += len2;
684 delete [] cmd2; // free memory for this command
685 } else {
686 // write the command
687 n = (int)write(mTo, cmd2, len2);
688 if (n < 0) {
689 if (errno != EAGAIN) return -2; // write error!
690 n = 0;
691 }
692 if (n == len2) {
693 delete [] cmd2; // success! delete the buffered command
694 } else {
695 // don't bother allocating any new memory,
696 // just use our cmd2 string as the new queue
697 if (n) memmove(cmd2, cmd2+n, len2-n);
698 mCmdQueue = cmd2;
699 mCmdQueueLen = len2 - n;
700 mCmdQueueSize = len2;
701 }
702 }
703 mCmdNum = cmdNum;
704 } else if (!mCmdQueue) {
705 return 0; // cmd is NULL, and queue is empty
706 }
707 return mCmdNum;
708 }
709
710 //------------------------------------------------------------------------------
711 // Wait for a command to complete (up to specified timeout)
712 // Inputs: timeout - maximum wait time (floating point seconds)
713 // Returns: command number on success, 0 on timeout, or <0 on error
714 int ExifTool::Complete(double timeout)
715 {
716 if (mCmdQueue) Command(); // try to send queued commands (if any)
717 double doneTime = getTime() + timeout;
718 int cmdNum;
719 for (;;) {
720 cmdNum = mStdout.Read();
721 if (cmdNum) break;
722 if (getTime() >= doneTime) break;
723 if (mCmdQueue) cmdNum = Command(); // keep sending queued commands
724 if (cmdNum <= 0) usleep(mWaitTime); // chill and have a beer
725 }
726 if (cmdNum > 0) {
727 // get errors from the same command (we know they must be coming,
728 // so loop as quickly as possible to read them, but impose a
729 // 1-second timeout just in case)
730 doneTime = getTime() + 1;
731 for (;;) {
732 int n = mStderr.Read();
733 if (n == cmdNum) break;
734 if (n < 0) { cmdNum = n; break; }
735 if (getTime() >= doneTime) { cmdNum = -4; break; }
736 }
737 }
738 return mLastComplete = cmdNum;
739 }
740
741 //------------------------------------------------------------------------------
742 // Get specified summary message
743 // Inputs: msg - message string in summary output
744 // Returns: corresponding number from summary statistics, or -1 if the
745 // specified message wasn't found
746 int ExifTool::GetSummary(const char *msg)
747 {
748 for (int out=0; out<2; ++out) {
749 // check stderr first because it isn't likely to be too long
750 char *str = out ? GetOutput() : GetError();
751 if (!str) continue;
752 char *pt = strstr(str, msg);
753 if (!pt || pt - str < 2 || pt[-1] != ' ' || !isdigit(pt[-2])) continue;
754 char ch = pt[strlen(msg)];
755 if (ch != '\n' && ch != '\r') continue; // message must end with a newline
756 pt -= 2;
757 while (pt > str && isdigit(pt[-1])) --pt;
758 return atoi(pt);
759 }
760 return -1; // message not found
761 }
762
763 //------------------------------------------------------------------------------
764 // Check to see if exiftool process is still running
765 int ExifTool::IsRunning()
766 {
767 int status;
768 if (mPid == -1) return 0;
769 if (waitpid(mPid, &status, WNOHANG)) {
770 // no more child process
771 mPid = -1;
772 return 0;
773 }
774 return 1; // yes!
775 }
776
777 // end
778
This page took 0.915727 seconds and 6 git commands to generate.