encode.pl 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680
  1. #!/usr/bin/perl
  2. use strict;
  3. use warnings;
  4. # Includes
  5. use IPC::Open3;
  6. use File::Basename;
  7. # Default configuration
  8. my $FORMAT = 'mp4';
  9. my $AUDIO_BITRATE = 192;
  10. my $QUALITY = 20;
  11. my $HD_QUALITY = 22;
  12. my $AUDIO_COPY = 0;
  13. my $STEREO_ONLY = 0;
  14. my $HEIGHT = undef();
  15. my $WIDTH = undef();
  16. my $AUDIO_EXCLUDE_REGEX = '\b(?:Chinese|Espanol|Francais|Japanese|Korean|Portugues|Thai)\b';
  17. my $SUB_INCLUDE_REGEX = '\b(?:English|Unknown|Closed\s+Captions)\b';
  18. # Applicaton configuration
  19. my $HD_WIDTH = 1350;
  20. my $MIN_VIDEO_WIDTH = 100;
  21. my $MAX_CROP_DIFF = .1;
  22. my $MAX_DURA_DIFF = 5;
  23. my @CODEC_ORDER = ('DTS-HD', 'DTS', 'PCM', 'AC3', 'AAC', 'OTHER');
  24. my %LANG_INCLUDE_ISO = ('639-1' => 1);
  25. my $HB_EXEC = $ENV{'HOME'} . '/bin/video/HandBrakeCLI';
  26. my $DEBUG = 0;
  27. # General parameters for HandBrake
  28. my @video_params = ('--markers', '--large-file', '--optimize', '--encoder', 'x264', '--detelecine', '--decomb', '--loose-anamorphic', '--modulus', '16', '--encopts', 'b-adapt=2:rc-lookahead=50');
  29. my @audio_params = ('--audio-copy-mask', 'dtshd,dts,ac3,aac', '--audio-fallback', 'ffac3', '--mixdown', 'dpl2');
  30. # Runtime debug mode
  31. if (defined($ENV{'DEBUG'}) && $ENV{'DEBUG'}) {
  32. $DEBUG = 1;
  33. }
  34. # Shortcut config
  35. if ($ENV{'MOBILE'}) {
  36. $ENV{'QUALITY'} = 25;
  37. $ENV{'HEIGHT'} = 720;
  38. $ENV{'WIDTH'} = 1280;
  39. $ENV{'AUDIO_BITRATE'} = 128;
  40. $ENV{'STEREO_ONLY'} = 1;
  41. }
  42. # Additional arguments for HandBrake
  43. # Split on spaces; if you need spaces you'll have to work out something else
  44. if ($ENV{'HANDBRAKE_ARGS'}) {
  45. my @args = split(/\s+/, $ENV{'HANDBRAKE_ARGS'});
  46. push(@video_params, @args);
  47. }
  48. # Allow overrides for audio languages
  49. if ($ENV{'AUDIO_EXCLUDE_REGEX'}) {
  50. $AUDIO_EXCLUDE_REGEX = $ENV{'AUDIO_EXCLUDE_REGEX'};
  51. }
  52. # Allow overrides for subtitle languages
  53. if ($ENV{'SUB_INCLUDE_REGEX'}) {
  54. $SUB_INCLUDE_REGEX = $ENV{'SUB_INCLUDE_REGEX'};
  55. }
  56. # Allow copy-only audio transfers (for use in re-encoding)
  57. if ($ENV{'AUDIO_COPY'}) {
  58. $AUDIO_COPY = 1;
  59. }
  60. # Allow AAC-only audio transfers (for use in mobile encoding)
  61. if ($ENV{'STEREO_ONLY'}) {
  62. $STEREO_ONLY = 1;
  63. }
  64. # Allow overrides for video quality
  65. if ($ENV{'QUALITY'}) {
  66. $QUALITY = $ENV{'QUALITY'};
  67. $HD_QUALITY = $ENV{'QUALITY'};
  68. }
  69. # Allow overrides for audio bitrate
  70. if ($ENV{'AUDIO_BITRATE'}) {
  71. $AUDIO_BITRATE = $ENV{'AUDIO_BITRATE'};
  72. }
  73. # Allow overrides for video height and width. The default is "same as source".
  74. if ($ENV{'HEIGHT'}) {
  75. $HEIGHT = $ENV{'HEIGHT'};
  76. }
  77. if ($ENV{'WIDTH'}) {
  78. $WIDTH = $ENV{'WIDTH'};
  79. }
  80. # Command-line parameters
  81. my ($in_file, $out_file, $title) = @ARGV;
  82. if (!defined($in_file) || length($in_file) < 1 || !-r $in_file) {
  83. die('Usage: ' . basename($0) . " in_file [out_file] [title]\n");
  84. }
  85. # Scan for title/track info
  86. my %titles = &scan($in_file);
  87. # Allow external subtitles for single-title files
  88. if (scalar(keys(%titles)) == 1) {
  89. my $srt_file = $in_file;
  90. $srt_file =~ s/\.\w{2,4}$/.srt/;
  91. if (!-r $srt_file) {
  92. $srt_file =~ s/\.\w{2,4}$/.ssa/;
  93. }
  94. if (-r $srt_file) {
  95. if ($DEBUG) {
  96. print STDERR 'Adding subtitles from: ' . $srt_file . "\n";
  97. }
  98. push(@video_params, '--srt-file', $srt_file);
  99. }
  100. }
  101. # Allow encoding of a specific title
  102. if ($title) {
  103. if ($title =~ /^\d+$/ && $title > 0) {
  104. if (!defined($titles{$title})) {
  105. die(basename($0) . ': Invalid title number: ' . $title . "\n");
  106. }
  107. my $selected_title = $titles{$title};
  108. %titles = ();
  109. $titles{$title} = $selected_title;
  110. } elsif ($title =~ /main/i) {
  111. my $max_title = 0;
  112. my $max_duration = 0;
  113. foreach my $title (keys(%titles)) {
  114. if (!$titles{$title}{'duration'}) {
  115. warn(basename($0) . ': Unknown duration for title: ' . $title . "\n");
  116. next;
  117. }
  118. my $new_max = 0;
  119. if (abs($titles{$title}{'duration'} - $max_duration) < $MAX_DURA_DIFF) {
  120. if ($titles{$title}{'aspect'} > $titles{$max_title}{'aspect'}) {
  121. $new_max = 1;
  122. } elsif ($titles{$title}{'size'}[0] > $titles{$max_title}{'size'}[0] || $titles{$title}{'size'}[1] > $titles{$max_title}{'size'}[1]) {
  123. $new_max = 1;
  124. }
  125. } elsif ($titles{$title}{'duration'} > $max_duration) {
  126. $new_max = 1;
  127. }
  128. if ($new_max) {
  129. $max_duration = $titles{$title}{'duration'};
  130. $max_title = $title;
  131. }
  132. }
  133. my $selected_title = $titles{$max_title};
  134. %titles = ();
  135. $titles{$max_title} = $selected_title;
  136. }
  137. }
  138. # Ensure we have an output file name
  139. # Force MKV output if the output file name is provided and ends in .MKV
  140. if (!defined($out_file) || length($out_file) < 1) {
  141. $out_file = $in_file;
  142. } else {
  143. my ($force_format) = $out_file =~ /\.(\w{2,4})$/;
  144. if (defined($force_format) && lc($force_format) eq 'mkv') {
  145. $FORMAT = 'mkv';
  146. }
  147. }
  148. # Keep the original format around so we can reset between tracks
  149. my $FORMAT_ORIG = $FORMAT;
  150. # Encode each title
  151. foreach my $title (keys(%titles)) {
  152. if ($DEBUG) {
  153. print STDERR 'Setting options for title: ' . $title . "\n";
  154. }
  155. # Reset
  156. $FORMAT = $FORMAT_ORIG;
  157. # Parse the title's audio and subtitle tracks
  158. my $scan = $titles{$title};
  159. my @audio = &audioOptions($scan);
  160. my @subs = &subOptions($scan);
  161. # Skip tracks that have no video
  162. if (scalar(@{ $scan->{'size'} }) < 2 || $scan->{'size'}[0] < $MIN_VIDEO_WIDTH) {
  163. print STDERR basename($0) . ': No video detected in: ' . $in_file . ':' . $title . ". Skipping title...\n";
  164. next;
  165. }
  166. # Skip tracks that have no audio
  167. if (scalar(@{ $scan->{'audio'} }) < 1 || scalar(@audio) < 1) {
  168. print STDERR basename($0) . ': No audio detected in: ' . $in_file . ':' . $title . ". Skipping title...\n";
  169. next;
  170. }
  171. # Set the audio quality for re-encoded tracks
  172. push(@audio, '--ab', $AUDIO_BITRATE);
  173. # Set the video quality, using $HD_QUALITY for images larger than $HD_WIDTH (to allow lower quality on HD streams)
  174. my $title_quality = $QUALITY;
  175. if ($scan->{'size'}[0] > $HD_WIDTH) {
  176. $title_quality = $HD_QUALITY;
  177. }
  178. # Override unlikely autocrop values
  179. if ( abs($scan->{'crop'}[0] - $scan->{'crop'}[1]) > $scan->{'size'}[0] * $MAX_CROP_DIFF
  180. || abs($scan->{'crop'}[2] - $scan->{'crop'}[3]) > $scan->{'size'}[0] * $MAX_CROP_DIFF)
  181. {
  182. print STDERR basename($0) . ': Overriding unlikely autocrop values: ' . join(':', @{ $scan->{'crop'} }) . "\n";
  183. my @crop = (0, 0, 0, 0);
  184. $scan->{'crop'} = \@crop;
  185. }
  186. # Force MKV output if the title contains PGS subtitles
  187. foreach my $track (values(%{ $scan->{'subtitle_parsed'} })) {
  188. if ($track->{'type'} eq 'PGS') {
  189. $FORMAT = 'mkv';
  190. last;
  191. }
  192. }
  193. # Force MKV output if the title contains DTS audio (technically MP4 is supported buy QuickTime hates it)
  194. foreach my $track (values(%{ $scan->{'audio_parsed'} })) {
  195. if ($track->{'codec'} =~ /DTS/i) {
  196. $FORMAT = 'mkv';
  197. last;
  198. }
  199. }
  200. # Select a file name extension that matches the format
  201. my $title_out_file = $out_file;
  202. $title_out_file =~ s/\.(?:\w{2,4}|dvdmedia)$//i;
  203. if ($FORMAT eq 'mkv') {
  204. $title_out_file .= '.mkv';
  205. } else {
  206. $title_out_file .= '.m4v';
  207. }
  208. # Force the title number into the output file name if there are multiple titles to be encoded
  209. if (scalar(keys(%titles)) > 1) {
  210. my $title_text = sprintf('%02d', $title);
  211. $title_out_file =~ s/(\.\w{2,4})$/\-${title_text}${1}/;
  212. }
  213. # Limit the maximum height and width, if any is specified
  214. if ($HEIGHT) {
  215. push(@video_params, '--maxHeight', $HEIGHT);
  216. }
  217. if ($WIDTH) {
  218. push(@video_params, '--maxWidth', $WIDTH);
  219. }
  220. # Output file
  221. if (uc($title_out_file) eq uc($in_file)) {
  222. $title_out_file =~ s/(\.\w{2,4})$/-recode${1}/;
  223. }
  224. # Build the arugment list
  225. my @args = ($HB_EXEC);
  226. push(@args, '--title', $title);
  227. push(@args, '--input', $in_file);
  228. push(@args, '--output', $title_out_file);
  229. push(@args, '--format', $FORMAT);
  230. push(@args, '--quality', $title_quality);
  231. push(@args, '--crop', join(':', @{ $scan->{'crop'} }));
  232. push(@args, @video_params);
  233. push(@args, @audio_params);
  234. push(@args, @audio);
  235. push(@args, @subs);
  236. if ($DEBUG) {
  237. print STDERR "\n" . join(' ', @args) . "\n\n";
  238. }
  239. # Sanity check
  240. if (-e $title_out_file) {
  241. print STDERR basename($0) . ': Output file exists: ' . $title_out_file . ". Skipping...\n";
  242. next;
  243. }
  244. # Run it
  245. my $child_out = '';
  246. my $child_in = '';
  247. my $pid = open3($child_in, $child_out, $child_out, @args);
  248. close($child_in);
  249. while (<$child_out>) {
  250. if ($DEBUG) {
  251. print STDERR $_;
  252. }
  253. }
  254. waitpid($pid, 0);
  255. close($child_out);
  256. # Provide the new file name if requested
  257. if ($ENV{'RECODE_OUTFILE'}) {
  258. print $title_out_file;
  259. }
  260. }
  261. # Cleanup
  262. exit(0);
  263. sub subOptions($) {
  264. my ($scan) = @_;
  265. my %tracks = ();
  266. foreach my $track (@{ $scan->{'subtitle'} }) {
  267. my ($language, $note, $iso, $text, $type) = $track->{'description'} =~ /^([^\(]+)(?:\s+\(([^\)]+)\))?\s+\(iso(\d+\-\d+)\:\s+\w\w\w\)\s+\((Text|Bitmap)\)\((CC|VOBSUB|PGS|SSA|TX3G|UTF\-\d+)\)/i;
  268. if (!defined($iso)) {
  269. print STDERR 'Could not parse subtitle description: ' . $track->{'description'} . "\n";
  270. # Temporarily exit on parsing errors -- at least until we're sure about this new parser
  271. #next;
  272. exit(1);
  273. }
  274. # Map text/bitmap into a boolean
  275. if ($text =~ /TEXT/i) {
  276. $text = 1;
  277. } else {
  278. $text = 0;
  279. }
  280. # Standardize the codes
  281. $iso = uc($iso);
  282. $type = uc($type);
  283. # Push all parsed data into an array
  284. my %data = ('language' => $language, 'note' => $note, 'iso' => $iso, 'text' => $text, 'type' => $type);
  285. $tracks{ $track->{'index'} } = \%data;
  286. # Print what we found
  287. if ($DEBUG) {
  288. print STDERR 'Found subtitle track: ';
  289. printHash(\%data);
  290. }
  291. }
  292. # Push the parsed data back up the chain
  293. $scan->{'subtitle_parsed'} = \%tracks;
  294. # Keep subtitles in our prefered langauges, and all text-based subtitles (they're small)
  295. my @keep = ();
  296. foreach my $index (keys(%tracks)) {
  297. if (isValidSubLanguage($tracks{$index}->{'language'}, $tracks{$index}->{'iso'})) {
  298. push(@keep, $index);
  299. } elsif ($tracks{$index}->{'text'}) {
  300. push(@keep, $index);
  301. } else {
  302. if ($DEBUG) {
  303. print STDERR 'Skipping subtitle ' . $index . ' due to language: ' . $tracks{$index}->{'language'} . "\n";
  304. }
  305. }
  306. }
  307. # Send back the argument string (if any)
  308. if (scalar(@keep) < 1) {
  309. return '';
  310. }
  311. return ('--subtitle', join(',', @keep));
  312. }
  313. sub audioOptions($) {
  314. my ($scan) = @_;
  315. # Type the audio tracks
  316. my %tracks = ();
  317. foreach my $track (@{ $scan->{'audio'} }) {
  318. my ($language, $codec, $note, $channels, $iso) = $track->{'description'} =~ /^([^\(]+)\s+\(([^\)]+)\)\s+(?:\(([^\)]*Commentary[^\)]*)\)\s+)?\((\d+\.\d+\s+ch|Dolby\s+Surround)\)(?:\s+\(iso(\d+\-\d+)\:\s+\w\w\w\))?/;
  319. if (!defined($channels)) {
  320. print STDERR 'Could not parse audio description: ' . $track->{'description'} . "\n";
  321. # Temporarily exit on parsing errors -- at least until we're sure about this new parser
  322. #next;
  323. exit(1);
  324. }
  325. # Decode the channels string to a number
  326. if ($channels =~ /(\d+\.\d+)\s+ch/i) {
  327. $channels = $1;
  328. } elsif ($channels =~ /Dolby\s+Surround/i) {
  329. $channels = 3.1;
  330. }
  331. # Standardize the codec
  332. foreach my $code (@CODEC_ORDER) {
  333. my $metacode = quotemeta($code);
  334. if ($codec =~ /${metacode}/i) {
  335. $codec = $code;
  336. last;
  337. } elsif ($code eq 'OTHER') {
  338. if ($codec =~ /MP3/i || $codec =~ /MPEG/i) {
  339. $codec = $code;
  340. } elsif ($codec eq 'truehd' || $codec eq 'dca') {
  341. print STDERR 'Found incompatible audio (' . $track->{'description'} . ') in track ' . $track->{'index'} . "\n";
  342. $codec = undef();
  343. } else {
  344. print STDERR 'Found unknown audio (' . $track->{'description'} . ') in track ' . $track->{'index'} . "\n";
  345. $codec = $code;
  346. }
  347. }
  348. }
  349. # Push all parsed data into the array
  350. my %data = ('language' => $language, 'codec' => $codec, 'channels' => $channels, 'iso' => $iso, 'note' => $note);
  351. $tracks{ $track->{'index'} } = \%data;
  352. # Print what we found
  353. if ($DEBUG) {
  354. print STDERR 'Found audio track: ';
  355. printHash(\%data);
  356. }
  357. }
  358. # Push the parsed data back up the chain
  359. $scan->{'audio_parsed'} = \%tracks;
  360. # Find the track with the most channels for each codec, and the highest number of channels among all types of tracks
  361. # Then choose the most desired codec among the set of codecs that contain the highest number of channels
  362. # This chooses the track with the most channels for the mixdown, and resolves ties using CODEC_ORDER
  363. my $mixdown = undef();
  364. my %bestByCodec = ();
  365. my $bestCodec = undef();
  366. my $mostChannels = 0;
  367. foreach my $codec (@CODEC_ORDER) {
  368. $bestByCodec{$codec} = findBestAudioTrack(\%tracks, $codec);
  369. if (defined($bestByCodec{$codec}) && (!defined($bestCodec) || $mostChannels < $tracks{ $bestByCodec{$codec} }->{'channels'})) {
  370. $bestCodec = $codec;
  371. $mostChannels = $tracks{ $bestByCodec{$codec} }->{'channels'};
  372. }
  373. }
  374. foreach my $codec (@CODEC_ORDER) {
  375. if (defined($bestByCodec{$codec}) && $tracks{ $bestByCodec{$codec} }->{'channels'} == $mostChannels) {
  376. $mixdown = $bestByCodec{$codec};
  377. last;
  378. }
  379. }
  380. # Sanity check
  381. if (!defined($mixdown) || $mixdown < 1) {
  382. print STDERR basename($0) . ": No usable audio tracks in title\n";
  383. return;
  384. }
  385. # Clear the mixdown selection if we're copying audio
  386. if ($AUDIO_COPY) {
  387. $mixdown = undef();
  388. }
  389. # Mixdown track first
  390. my @audio_tracks = ();
  391. if (defined($mixdown) && $mixdown > 0) {
  392. if ($DEBUG) {
  393. print STDERR 'Using track ' . $mixdown . " as default AAC audio\n";
  394. if ($tracks{$mixdown}->{'channels'} > 2) {
  395. print STDERR "\tMixing down with Dolby Pro Logic II encoding\n";
  396. }
  397. }
  398. my %track = ('index' => $mixdown, 'encoder' => 'ca_aac');
  399. push(@audio_tracks, \%track);
  400. }
  401. # Keep all other audio tracks, unless STEREO_ONLY is set
  402. if (!$STEREO_ONLY) {
  403. # Passthru DTS-MA, DTS, AC3, and AAC
  404. # Keep other audio tracks, but recode to AAC (using Handbrake's audio-copy-mask/audio-fallback feature)
  405. foreach my $index (keys(%tracks)) {
  406. if ($mixdown == $index && $tracks{$index}->{'codec'} eq 'OTHER' && $tracks{$index}->{'channels'} <= 2) {
  407. if ($DEBUG) {
  408. print STDERR 'Skipping recode of track ' . $index . ' since it is already used as the default track and contains only ' . $tracks{$index}->{'channels'} . " channels\n";
  409. }
  410. next;
  411. } elsif (!$tracks{$index}->{'codec'}) {
  412. if ($DEBUG) {
  413. print STDERR 'Skipping track ' . $index . " due to invalid codec\n";
  414. }
  415. next;
  416. } elsif (!isValidAudioLanguage($tracks{$index}->{'language'}, $tracks{$index}->{'iso'})) {
  417. if ($DEBUG) {
  418. print STDERR 'Skipping track ' . $index . ' due to language: ' . $tracks{$index}->{'language'} . "\n";
  419. }
  420. next;
  421. } else {
  422. my %track = ('index' => $index, 'encoder' => 'copy');
  423. push(@audio_tracks, \%track);
  424. }
  425. }
  426. }
  427. # Consolidate from the hashes
  428. my @output_tracks = ();
  429. my @output_encoders = ();
  430. foreach my $track (@audio_tracks) {
  431. push(@output_tracks, $track->{'index'});
  432. push(@output_encoders, $track->{'encoder'});
  433. }
  434. # Send back the argument strings
  435. return ('--audio', join(',', @output_tracks), '--aencoder', join(',', @output_encoders));
  436. }
  437. sub scan($) {
  438. my ($in_file) = @_;
  439. # Fork to scan the file
  440. my $child_out = '';
  441. my $pid = open3('<&STDIN', $child_out, $child_out, $HB_EXEC, '--title', '0', '--input', $in_file);
  442. # Loop through the output
  443. my $scan;
  444. my %titles = ();
  445. my $inTitle = 0;
  446. my $zone = '';
  447. while (<$child_out>) {
  448. if (!$inTitle && m/scan thread found (\d+) valid title/i) {
  449. if ($DEBUG) {
  450. print STDERR 'Found ' . $1 . " titles in source\n";
  451. }
  452. } elsif (m/^\s+Stream \#0\.(\d+)\(\w+\)\:\s+(.*)/) {
  453. my $stream = $1;
  454. my $desc = $2;
  455. } elsif (m/^\s*\+\s+title\s+(\d+)\:/) {
  456. # Save the current title (if any)
  457. if ($inTitle) {
  458. $titles{$inTitle} = $scan;
  459. }
  460. # Grab the new title number
  461. $inTitle = $1;
  462. # Init the data collectors
  463. my @audio = ();
  464. my @crop = ();
  465. my @subtitle = ();
  466. my @size = ();
  467. my %tmp = (
  468. 'audio' => \@audio,
  469. 'crop' => \@crop,
  470. 'subtitle' => \@subtitle,
  471. 'size' => \@size,
  472. 'duration' => 0,
  473. 'aspect' => 0
  474. );
  475. $scan = \%tmp;
  476. if ($DEBUG) {
  477. print STDERR 'Found data for title ' . $1 . "\n";
  478. }
  479. } elsif ($inTitle) {
  480. if (/^\s*\+\s+size: (\d+)x(\d+)/) {
  481. push(@{ $scan->{'size'} }, $1, $2);
  482. if ($DEBUG) {
  483. print STDERR 'Size: ' . join('x', @{ $scan->{'size'} }) . "\n";
  484. }
  485. if (/\s+display aspect\: (\d*\.\d+)/) {
  486. $scan->{'aspect'} = $1;
  487. if ($DEBUG) {
  488. print STDERR 'Aspect: ' . $scan->{'aspect'} . "\n";
  489. }
  490. }
  491. } elsif (/^\s*\+\s+duration\:\s+(\d+)\:(\d+)\:(\d+)/) {
  492. $scan->{'duration'} = ($1 * 3600) + ($2 * 60) + $3;
  493. if ($DEBUG) {
  494. print STDERR 'Duration: ' . $scan->{'duration'} . "\n";
  495. }
  496. } elsif (/^\s*\+\s+autocrop\:\s+(\d+)\/(\d+)\/(\d+)\/(\d+)/) {
  497. push(@{ $scan->{'crop'} }, $1, $2, $3, $4);
  498. if ($DEBUG) {
  499. print STDERR 'Crop: ' . join('/', @{ $scan->{'crop'} }) . "\n";
  500. }
  501. } elsif ($zone ne 'audio' && /^\s*\+\s+audio\s+tracks\:\s*$/) {
  502. $zone = 'audio';
  503. } elsif ($zone eq 'audio' && /^\s*\+\s+(\d+)\,\s+(.*)/) {
  504. my %track = ('index' => $1, 'description' => $2);
  505. push(@{ $scan->{'audio'} }, \%track);
  506. if ($DEBUG) {
  507. print STDERR 'Audio Track #' . $track{'index'} . ': ' . $track{'description'} . "\n";
  508. }
  509. } elsif ($zone ne 'subtitle' && /^\s*\+\s+subtitle\s+tracks\:\s*$/) {
  510. $zone = 'subtitle';
  511. } elsif ($zone eq 'subtitle' && m/^\s*\+\s+(\d+)\,\s+(.*)$/) {
  512. my %track = ('index' => $1, 'description' => $2);
  513. push(@{ $scan->{'subtitle'} }, \%track);
  514. if ($DEBUG) {
  515. print STDERR 'Subtitle Track #' . $track{'index'} . ': ' . $track{'description'} . "\n";
  516. }
  517. }
  518. }
  519. }
  520. # Save the last title (if any)
  521. if ($inTitle) {
  522. $titles{$inTitle} = $scan;
  523. }
  524. # Cleanup the scan process
  525. waitpid($pid, 0);
  526. close($child_out);
  527. # Sanity check
  528. if (scalar(keys(%titles)) < 1) {
  529. die(basename($0) . ': Did not find any titles in file: ' . $in_file . "\n");
  530. }
  531. # Return
  532. return %titles;
  533. }
  534. sub findBestAudioTrack($$) {
  535. my ($tracks, $codec) = @_;
  536. my $best = undef();
  537. my $channels = 0;
  538. for my $index (keys(%{$tracks})) {
  539. my $track = $tracks->{$index};
  540. # Skip tracks not in the specified codec
  541. if (!$track->{'codec'} || $track->{'codec'} ne $codec) {
  542. next;
  543. }
  544. # Skip foreign language tracks
  545. if (!isValidAudioLanguage($track->{'language'}, $track->{'iso'})) {
  546. next;
  547. }
  548. # Find the track with the most channels (Ófirst wins)
  549. if (!defined($best) || $track->{'channels'} > $channels) {
  550. $best = $index;
  551. $channels = $track->{'channels'};
  552. }
  553. }
  554. return $best;
  555. }
  556. sub isValidSubLanguage($) {
  557. my ($lang, $iso) = @_;
  558. if (scalar(keys(%LANG_INCLUDE_ISO)) && $LANG_INCLUDE_ISO{$iso}) {
  559. return 1;
  560. } elsif ($SUB_INCLUDE_REGEX && $lang =~ /${SUB_INCLUDE_REGEX}/i) {
  561. return 1;
  562. }
  563. return 0;
  564. }
  565. sub isValidAudioLanguage($) {
  566. my ($lang, $iso) = @_;
  567. if (scalar(keys(%LANG_INCLUDE_ISO)) && $LANG_INCLUDE_ISO{$iso}) {
  568. return 1;
  569. } elsif ($AUDIO_EXCLUDE_REGEX && $lang =~ /${AUDIO_EXCLUDE_REGEX}/i) {
  570. return 0;
  571. }
  572. return 1;
  573. }
  574. sub printHash($) {
  575. my ($data) = @_;
  576. my $first = 1;
  577. foreach my $key (keys(%{$data})) {
  578. if (defined($data->{$key})) {
  579. if ($first) {
  580. $first = 0;
  581. } else {
  582. print STDERR ', ';
  583. }
  584. print STDERR $key . ' => ' . $data->{$key};
  585. }
  586. }
  587. print STDERR "\n";
  588. }