encode.pl 19 KB

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