]>
git.datanom.net - lensdb.git/blob - lib/exiftool/ExifTool.cpp
1 //------------------------------------------------------------------------------
4 // Description: C++ library interface to Perl exiftool application script
6 // License: Copyright 2013-2019, Phil Harvey (philharvey66 at gmail.com)
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.
13 // Created: 2013-11-23 - Phil Harvey
14 //------------------------------------------------------------------------------
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
32 const char *kDefaultExec
= "exiftool";
34 static int sBrokenPipe
= -1;
36 int ExifTool::sNoSigPipe
= 0;
37 int ExifTool::sNoWatchdog
= 0;
39 //------------------------------------------------------------------------------
41 static void sigPipeAction(int sig
)
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
)
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));
60 // must un-escape this character
64 // decode 2-digit hex character
66 for (int i
=0; i
<2; ++i
) {
67 char nibble
= *(src
++);
68 if (nibble
>= '0' && nibble
<= '9') {
70 } else if (nibble
>= 'A' && nibble
<= 'F') {
72 } else if (nibble
>= 'a' && nibble
<= 'f') {
75 ch
= 0; // (shouldn't happen)
78 ch
= (ch
<< 4) + nibble
;
90 case '\0': // (shouldn't happen, but just to be safe)
92 return((int)(dst
- str
));
94 // pass any other character straight through
103 return((int)(dst
- str
));
106 //------------------------------------------------------------------------------
107 // get current hi-resolution time
108 static double getTime()
112 gettimeofday(&tv
,&tz
);
113 return(tv
.tv_sec
+ 1e-6 * tv
.tv_usec
);
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)
125 int to
[2], from
[2], err
[2];
128 args
[1] = kDefaultExec
;
129 args
[2] = "-stay_open";
140 args
[firstArg
] = exec
? exec
: kDefaultExec
;
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!
160 // fork and exec exiftool
164 // this is our exiftool thread
168 dup2(to
[0], STDIN_FILENO
);
169 dup2(from
[1], STDOUT_FILENO
);
170 dup2(err
[1], STDERR_FILENO
);
174 execvp(args
[firstArg
], (char * const *)args
+ firstArg
);
175 // (if execvp succeeds, it will never return)
178 // this is our working thread
182 // allocate memory for exiftool response and error messages
183 mStdout
.Init(from
[0], mPid
, kOutBlockSize
);
184 mStderr
.Init(err
[0], mPid
, kErrBlockSize
);
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
197 // monitor the main program and clean up if it dies
198 // (under normal conditions this watchdog process
199 // is killed in the destructor)
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
206 exit(0); // exit the watchdog process
213 //------------------------------------------------------------------------------
214 // Terminate exiftool application process and close files
215 ExifTool::~ExifTool()
220 Command("-stay_open\nfalse\n");
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
231 usleep(100); // relax
234 kill(mWatchdog
, SIGINT
); // kill our watchdog process
235 waitpid(mWatchdog
, NULL
, 0);// avoid zombie
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
)
251 int cmdNum
= ExtractInfo(file
, opts
);
253 // error unless command number is > 0
254 if (cmdNum
<= 0) return (TagInfo
*)NULL
;
256 return GetInfo(cmdNum
, timeout
);
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
)
266 if (!file
) return -5;
268 // prepare command arguments for exiftool
269 int flen
= (int)strlen(file
);
270 int olen
= opts
? (int)strlen(opts
) : 0;
272 char *buff
= new char[flen
+ olen
+ 64];
273 if (!buff
) return -3; // out of memory!
274 memcpy(buff
, file
, flen
);
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");
280 // add extra options specified by the caller
283 strcat(buff
, "\n"); // (to be safe; blank lines are ignored)
286 // send the command to exiftool
287 int cmdNum
= Command(buff
);
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
)
304 TagInfo
*info
= (TagInfo
*)NULL
;
305 TagInfo
*next
= (TagInfo
*)NULL
;
306 TagInfo
*infoList
= (TagInfo
*)NULL
;
308 // wait for specified command to complete
311 int n
= Complete(timeout
);
312 if (n
<= 0) return info
;
313 if (n
== cmdNum
|| !cmdNum
) break;
315 } else if (mLastComplete
<= 0) {
319 // parse the response string, line by line
320 char *pt
= mStdout
.GetString();
321 if (!pt
) return info
;
323 int mode
= 0; // 0=looking for tag name, 1=tag properties
326 // find the end of this line
328 pt
= strchr(pt
, '\n');
330 *pt
= '\0'; // null terminate this line
331 ++pt
; // continue at next line
332 // scan for opening quote
333 p0
= strchr(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
338 // (name and value are guaranteed to exist)
340 info
->value
= new char[1];
341 if (!info
->value
) break;
342 info
->value
[0] = '\0';
345 info
->num
= info
->value
;
346 info
->numLen
= info
->valueLen
;
349 mode
= 0; // look for next tag name
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
358 // extract tag/group names
362 if (ch
== '"' || ch
== ':') {
363 int n
= (int)(p1
- p0
);
364 char *str
= new char[n
+ 1];
369 next
->name
= str
; // save tag name
374 if (!memcmp(str
, "Copy", 4)) {
375 next
->copyNum
= atoi(str
+4);
376 delete [] str
; // done with this string
379 next
->group
[g
] = str
; // save group name
386 if (!next
->name
) continue;
387 // file name given by line like: "SourceFile" => "images/a.jpg",
388 if (!strcmp(next
->name
,"SourceFile")) {
390 if (*p2
== '\r') --p2
; // skip Windows CR
391 if (*p2
== ',') --p2
;
392 if (*p2
!= '"') continue;
393 int n
= (int)(p2
- p1
- 6);
395 char *str
= new char[n
+1];
397 memcpy(str
, p1
+6, n
);
399 next
->value
= next
->num
= str
;
400 next
->valueLen
= next
->numLen
= n
;
402 mode
= 1; // read tag properties next
404 // add to linked list of information
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
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
428 if (!strcmp(p0
, "desc")) {
430 } else if (!strcmp(p0
, "id")) {
432 } else if (!strcmp(p0
, "num")) {
434 info
->numLen
= n
- 1; // save length too (could be binary data)
435 } else if (!strcmp(p0
, "val")) {
437 info
->valueLen
= n
- 1; // save length too (could be binary data)
439 continue; // (shouldn't happen)
443 memcpy(*dst
, p1
, n
); // copy property value
446 if (next
) delete next
;
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
)
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
);
470 if (value
) len
= (int)strlen(value
);
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
;
482 // place at the end of the linked list
483 TagInfo
**pt
= &mWriteInfo
;
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
)
509 if (!file
) return -5;
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
;
518 int pos
= (int)strlen(file
);
522 // use internal new value list if not specified
523 if (!info
) info
= mWriteInfo
;
525 // prepare assignment arguments for exiftool, looping through all tags to write
527 if (!info
->name
|| strlen(info
->name
) > 100 || !strcmp(info
->name
, "SourceFile")) {
531 // construct the tag name
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
542 strcat(tag
, info
->name
);
543 // which value are we writing (converted or numerical?)
544 char *val
= info
->value
;
545 int valLen
= info
->valueLen
;
548 valLen
= info
->numLen
;
549 if (val
) strcat(tag
, "#"); // write numerical value
551 int tagLen
= (int)strlen(tag
);
552 int origLen
= valLen
;
553 // count the number of characters in the value that need escaping
556 char *end
= pt
+ origLen
;
560 if (ch
==10 || ch
=='&' || ch
=='\0') ++count
;
562 valLen
+= count
* 4; // 4 extra bytes for each escaped character
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
);
576 memcpy(buff
+pos
, tag
, tagLen
);
579 if (valLen
== origLen
) {
581 memcpy(buff
+pos
, val
, valLen
);
585 // escape newlines and '&' characters in the value
587 char *end
= pt
+ origLen
;
588 char *dst
= buff
+ pos
;
592 memcpy(dst
, " ", 5);
594 } else if (ch
== 0) {
595 memcpy(dst
, "�", 5);
597 } else if (ch
== '&') {
598 memcpy(dst
, "&", 5);
604 pos
= (int)(dst
- buff
);
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
616 strcpy(buff
+pos
, opts
);
618 buff
[pos
++] = '\n'; // (just in case)
621 int cmdNum
= Command(buff
);
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
)
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
640 n
= (int)write(mTo
, mCmdQueue
, mCmdQueueLen
);
642 if (errno
!= EAGAIN
) return -2; // write error!
645 if (n
== mCmdQueueLen
) {
650 memmove(mCmdQueue
, mCmdQueue
+n
, mCmdQueueLen
-n
);
655 // increment to next command number
656 int cmdNum
= mCmdNum
+ 1;
657 if (cmdNum
> 99999) cmdNum
= 1;
659 // compose full command string (cmd2)
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
669 // add command to the queue if not empty
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
);
679 mCmdQueueSize
= newSize
;
681 // copy this command into the queue
682 memcpy(mCmdQueue
+mCmdQueueLen
, cmd2
, len2
);
683 mCmdQueueLen
+= len2
;
684 delete [] cmd2
; // free memory for this command
687 n
= (int)write(mTo
, cmd2
, len2
);
689 if (errno
!= EAGAIN
) return -2; // write error!
693 delete [] cmd2
; // success! delete the buffered command
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
);
699 mCmdQueueLen
= len2
- n
;
700 mCmdQueueSize
= len2
;
704 } else if (!mCmdQueue
) {
705 return 0; // cmd is NULL, and queue is empty
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
)
716 if (mCmdQueue
) Command(); // try to send queued commands (if any)
717 double doneTime
= getTime() + timeout
;
720 cmdNum
= mStdout
.Read();
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
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;
732 int n
= mStderr
.Read();
733 if (n
== cmdNum
) break;
734 if (n
< 0) { cmdNum
= n
; break; }
735 if (getTime() >= doneTime
) { cmdNum
= -4; break; }
738 return mLastComplete
= cmdNum
;
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
)
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();
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
757 while (pt
> str
&& isdigit(pt
[-1])) --pt
;
760 return -1; // message not found
763 //------------------------------------------------------------------------------
764 // Check to see if exiftool process is still running
765 int ExifTool::IsRunning()
768 if (mPid
== -1) return 0;
769 if (waitpid(mPid
, &status
, WNOHANG
)) {
770 // no more child process
This page took 1.749606 seconds and 6 git commands to generate.