encode.pl 21 KB

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