encode.pl 19 KB

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