You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

497 lines
16KB

  1. /*
  2. * MOV, 3GP, MP4 muxer RTP hinting
  3. * Copyright (c) 2010 Martin Storsjo
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * FFmpeg is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with FFmpeg; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. #include "movenc.h"
  22. #include "libavutil/intreadwrite.h"
  23. #include "internal.h"
  24. int ff_mov_init_hinting(AVFormatContext *s, int index, int src_index)
  25. {
  26. MOVMuxContext *mov = s->priv_data;
  27. MOVTrack *track = &mov->tracks[index];
  28. MOVTrack *src_track = &mov->tracks[src_index];
  29. AVStream *src_st = s->streams[src_index];
  30. int ret = AVERROR(ENOMEM);
  31. AVOutputFormat *rtp_format = av_guess_format("rtp", NULL, NULL);
  32. track->tag = MKTAG('r','t','p',' ');
  33. track->src_track = src_index;
  34. if (!rtp_format) {
  35. ret = AVERROR(ENOENT);
  36. goto fail;
  37. }
  38. track->enc = avcodec_alloc_context();
  39. if (!track->enc)
  40. goto fail;
  41. track->enc->codec_type = AVMEDIA_TYPE_DATA;
  42. track->enc->codec_tag = track->tag;
  43. track->rtp_ctx = avformat_alloc_context();
  44. if (!track->rtp_ctx)
  45. goto fail;
  46. track->rtp_ctx->oformat = rtp_format;
  47. if (!av_new_stream(track->rtp_ctx, 0))
  48. goto fail;
  49. /* Copy stream parameters */
  50. track->rtp_ctx->streams[0]->sample_aspect_ratio =
  51. src_st->sample_aspect_ratio;
  52. /* Remove the allocated codec context, link to the original one
  53. * instead, to give the rtp muxer access to codec parameters. */
  54. av_free(track->rtp_ctx->streams[0]->codec);
  55. track->rtp_ctx->streams[0]->codec = src_st->codec;
  56. if ((ret = url_open_dyn_packet_buf(&track->rtp_ctx->pb,
  57. RTP_MAX_PACKET_SIZE)) < 0)
  58. goto fail;
  59. ret = av_write_header(track->rtp_ctx);
  60. if (ret)
  61. goto fail;
  62. /* Copy the RTP AVStream timebase back to the hint AVStream */
  63. track->timescale = track->rtp_ctx->streams[0]->time_base.den;
  64. /* Mark the hinted track that packets written to it should be
  65. * sent to this track for hinting. */
  66. src_track->hint_track = index;
  67. return 0;
  68. fail:
  69. av_log(s, AV_LOG_WARNING,
  70. "Unable to initialize hinting of stream %d\n", src_index);
  71. if (track->rtp_ctx && track->rtp_ctx->pb) {
  72. uint8_t *buf;
  73. url_close_dyn_buf(track->rtp_ctx->pb, &buf);
  74. av_free(buf);
  75. }
  76. if (track->rtp_ctx && track->rtp_ctx->streams[0]) {
  77. av_metadata_free(&track->rtp_ctx->streams[0]->metadata);
  78. av_free(track->rtp_ctx->streams[0]);
  79. }
  80. if (track->rtp_ctx) {
  81. av_metadata_free(&track->rtp_ctx->metadata);
  82. av_free(track->rtp_ctx->priv_data);
  83. av_freep(&track->rtp_ctx);
  84. }
  85. av_freep(&track->enc);
  86. /* Set a default timescale, to avoid crashes in dump_format */
  87. track->timescale = 90000;
  88. return ret;
  89. }
  90. /**
  91. * Remove the first sample from the sample queue.
  92. */
  93. static void sample_queue_pop(HintSampleQueue *queue)
  94. {
  95. if (queue->len <= 0)
  96. return;
  97. if (queue->samples[0].own_data)
  98. av_free(queue->samples[0].data);
  99. queue->len--;
  100. memmove(queue->samples, queue->samples + 1, sizeof(HintSample)*queue->len);
  101. }
  102. /**
  103. * Empty the sample queue, releasing all memory.
  104. */
  105. static void sample_queue_free(HintSampleQueue *queue)
  106. {
  107. int i;
  108. for (i = 0; i < queue->len; i++)
  109. if (queue->samples[i].own_data)
  110. av_free(queue->samples[i].data);
  111. av_freep(&queue->samples);
  112. queue->len = 0;
  113. queue->size = 0;
  114. }
  115. /**
  116. * Add a reference to the sample data to the sample queue. The data is
  117. * not copied. sample_queue_retain should be called before pkt->data
  118. * is reused/freed.
  119. */
  120. static void sample_queue_push(HintSampleQueue *queue, AVPacket *pkt, int sample)
  121. {
  122. /* No need to keep track of smaller samples, since describing them
  123. * with immediates is more efficient. */
  124. if (pkt->size <= 14)
  125. return;
  126. if (!queue->samples || queue->len >= queue->size) {
  127. HintSample* samples;
  128. queue->size += 10;
  129. samples = av_realloc(queue->samples, sizeof(HintSample)*queue->size);
  130. if (!samples)
  131. return;
  132. queue->samples = samples;
  133. }
  134. queue->samples[queue->len].data = pkt->data;
  135. queue->samples[queue->len].size = pkt->size;
  136. queue->samples[queue->len].sample_number = sample;
  137. queue->samples[queue->len].offset = 0;
  138. queue->samples[queue->len].own_data = 0;
  139. queue->len++;
  140. }
  141. /**
  142. * Make local copies of all referenced sample data in the queue.
  143. */
  144. static void sample_queue_retain(HintSampleQueue *queue)
  145. {
  146. int i;
  147. for (i = 0; i < queue->len; ) {
  148. HintSample *sample = &queue->samples[i];
  149. if (!sample->own_data) {
  150. uint8_t* ptr = av_malloc(sample->size);
  151. if (!ptr) {
  152. /* Unable to allocate memory for this one, remove it */
  153. memmove(queue->samples + i, queue->samples + i + 1,
  154. sizeof(HintSample)*(queue->len - i - 1));
  155. queue->len--;
  156. continue;
  157. }
  158. memcpy(ptr, sample->data, sample->size);
  159. sample->data = ptr;
  160. sample->own_data = 1;
  161. }
  162. i++;
  163. }
  164. }
  165. /**
  166. * Find matches of needle[n_pos ->] within haystack. If a sufficiently
  167. * large match is found, matching bytes before n_pos are included
  168. * in the match, too (within the limits of the arrays).
  169. *
  170. * @param haystack buffer that may contain parts of needle
  171. * @param h_len length of the haystack buffer
  172. * @param needle buffer containing source data that have been used to
  173. * construct haystack
  174. * @param n_pos start position in needle used for looking for matches
  175. * @param n_len length of the needle buffer
  176. * @param match_h_offset_ptr offset of the first matching byte within haystack
  177. * @param match_n_offset_ptr offset of the first matching byte within needle
  178. * @param match_len_ptr length of the matched segment
  179. * @return 0 if a match was found, < 0 if no match was found
  180. */
  181. static int match_segments(const uint8_t *haystack, int h_len,
  182. const uint8_t *needle, int n_pos, int n_len,
  183. int *match_h_offset_ptr, int *match_n_offset_ptr,
  184. int *match_len_ptr)
  185. {
  186. int h_pos;
  187. for (h_pos = 0; h_pos < h_len; h_pos++) {
  188. int match_len = 0;
  189. int match_h_pos, match_n_pos;
  190. /* Check how many bytes match at needle[n_pos] and haystack[h_pos] */
  191. while (h_pos + match_len < h_len && n_pos + match_len < n_len &&
  192. needle[n_pos + match_len] == haystack[h_pos + match_len])
  193. match_len++;
  194. if (match_len <= 8)
  195. continue;
  196. /* If a sufficiently large match was found, try to expand
  197. * the matched segment backwards. */
  198. match_h_pos = h_pos;
  199. match_n_pos = n_pos;
  200. while (match_n_pos > 0 && match_h_pos > 0 &&
  201. needle[match_n_pos - 1] == haystack[match_h_pos - 1]) {
  202. match_n_pos--;
  203. match_h_pos--;
  204. match_len++;
  205. }
  206. if (match_len <= 14)
  207. continue;
  208. *match_h_offset_ptr = match_h_pos;
  209. *match_n_offset_ptr = match_n_pos;
  210. *match_len_ptr = match_len;
  211. return 0;
  212. }
  213. return -1;
  214. }
  215. /**
  216. * Look for segments in samples in the sample queue matching the data
  217. * in ptr. Samples not matching are removed from the queue. If a match
  218. * is found, the next time it will look for matches starting from the
  219. * end of the previous matched segment.
  220. *
  221. * @param data data to find matches for in the sample queue
  222. * @param len length of the data buffer
  223. * @param queue samples used for looking for matching segments
  224. * @param pos the offset in data of the matched segment
  225. * @param match_sample the number of the sample that contained the match
  226. * @param match_offset the offset of the matched segment within the sample
  227. * @param match_len the length of the matched segment
  228. * @return 0 if a match was found, < 0 if no match was found
  229. */
  230. static int find_sample_match(const uint8_t *data, int len,
  231. HintSampleQueue *queue, int *pos,
  232. int *match_sample, int *match_offset,
  233. int *match_len)
  234. {
  235. while (queue->len > 0) {
  236. HintSample *sample = &queue->samples[0];
  237. /* If looking for matches in a new sample, skip the first 5 bytes,
  238. * since they often may be modified/removed in the output packet. */
  239. if (sample->offset == 0 && sample->size > 5)
  240. sample->offset = 5;
  241. if (match_segments(data, len, sample->data, sample->offset,
  242. sample->size, pos, match_offset, match_len) == 0) {
  243. *match_sample = sample->sample_number;
  244. /* Next time, look for matches at this offset, with a little
  245. * margin to this match. */
  246. sample->offset = *match_offset + *match_len + 5;
  247. if (sample->offset + 10 >= sample->size)
  248. sample_queue_pop(queue); /* Not enough useful data left */
  249. return 0;
  250. }
  251. if (sample->offset < 10 && sample->size > 20) {
  252. /* No match found from the start of the sample,
  253. * try from the middle of the sample instead. */
  254. sample->offset = sample->size/2;
  255. } else {
  256. /* No match for this sample, remove it */
  257. sample_queue_pop(queue);
  258. }
  259. }
  260. return -1;
  261. }
  262. static void output_immediate(const uint8_t *data, int size,
  263. ByteIOContext *out, int *entries)
  264. {
  265. while (size > 0) {
  266. int len = size;
  267. if (len > 14)
  268. len = 14;
  269. put_byte(out, 1); /* immediate constructor */
  270. put_byte(out, len); /* amount of valid data */
  271. put_buffer(out, data, len);
  272. data += len;
  273. size -= len;
  274. for (; len < 14; len++)
  275. put_byte(out, 0);
  276. (*entries)++;
  277. }
  278. }
  279. static void output_match(ByteIOContext *out, int match_sample,
  280. int match_offset, int match_len, int *entries)
  281. {
  282. put_byte(out, 2); /* sample constructor */
  283. put_byte(out, 0); /* track reference */
  284. put_be16(out, match_len);
  285. put_be32(out, match_sample);
  286. put_be32(out, match_offset);
  287. put_be16(out, 1); /* bytes per block */
  288. put_be16(out, 1); /* samples per block */
  289. (*entries)++;
  290. }
  291. static void describe_payload(const uint8_t *data, int size,
  292. ByteIOContext *out, int *entries,
  293. HintSampleQueue *queue)
  294. {
  295. /* Describe the payload using different constructors */
  296. while (size > 0) {
  297. int match_sample, match_offset, match_len, pos;
  298. if (find_sample_match(data, size, queue, &pos, &match_sample,
  299. &match_offset, &match_len) < 0)
  300. break;
  301. output_immediate(data, pos, out, entries);
  302. data += pos;
  303. size -= pos;
  304. output_match(out, match_sample, match_offset, match_len, entries);
  305. data += match_len;
  306. size -= match_len;
  307. }
  308. output_immediate(data, size, out, entries);
  309. }
  310. /**
  311. * Write an RTP hint (that may contain one or more RTP packets)
  312. * for the packets in data. data contains one or more packets with a
  313. * BE32 size header.
  314. *
  315. * @param out buffer where the hints are written
  316. * @param data buffer containing RTP packets
  317. * @param size the size of the data buffer
  318. * @param trk the MOVTrack for the hint track
  319. * @param pts pointer where the timestamp for the written RTP hint is stored
  320. * @return the number of RTP packets in the written hint
  321. */
  322. static int write_hint_packets(ByteIOContext *out, const uint8_t *data,
  323. int size, MOVTrack *trk, int64_t *pts)
  324. {
  325. int64_t curpos;
  326. int64_t count_pos, entries_pos;
  327. int count = 0, entries;
  328. count_pos = url_ftell(out);
  329. /* RTPsample header */
  330. put_be16(out, 0); /* packet count */
  331. put_be16(out, 0); /* reserved */
  332. while (size > 4) {
  333. uint32_t packet_len = AV_RB32(data);
  334. uint16_t seq;
  335. uint32_t ts;
  336. data += 4;
  337. size -= 4;
  338. if (packet_len > size || packet_len <= 12)
  339. break;
  340. if (data[1] >= 200 && data[1] <= 204) {
  341. /* RTCP packet, just skip */
  342. data += packet_len;
  343. size -= packet_len;
  344. continue;
  345. }
  346. if (packet_len > trk->max_packet_size)
  347. trk->max_packet_size = packet_len;
  348. seq = AV_RB16(&data[2]);
  349. ts = AV_RB32(&data[4]);
  350. if (trk->prev_rtp_ts == 0)
  351. trk->prev_rtp_ts = ts;
  352. /* Unwrap the 32-bit RTP timestamp that wraps around often
  353. * into a not (as often) wrapping 64-bit timestamp. */
  354. trk->cur_rtp_ts_unwrapped += (int32_t) (ts - trk->prev_rtp_ts);
  355. trk->prev_rtp_ts = ts;
  356. if (*pts == AV_NOPTS_VALUE)
  357. *pts = trk->cur_rtp_ts_unwrapped;
  358. count++;
  359. /* RTPpacket header */
  360. put_be32(out, 0); /* relative_time */
  361. put_buffer(out, data, 2); /* RTP header */
  362. put_be16(out, seq); /* RTPsequenceseed */
  363. put_be16(out, 0); /* reserved + flags */
  364. entries_pos = url_ftell(out);
  365. put_be16(out, 0); /* entry count */
  366. data += 12;
  367. size -= 12;
  368. packet_len -= 12;
  369. entries = 0;
  370. /* Write one or more constructors describing the payload data */
  371. describe_payload(data, packet_len, out, &entries, &trk->sample_queue);
  372. data += packet_len;
  373. size -= packet_len;
  374. curpos = url_ftell(out);
  375. url_fseek(out, entries_pos, SEEK_SET);
  376. put_be16(out, entries);
  377. url_fseek(out, curpos, SEEK_SET);
  378. }
  379. curpos = url_ftell(out);
  380. url_fseek(out, count_pos, SEEK_SET);
  381. put_be16(out, count);
  382. url_fseek(out, curpos, SEEK_SET);
  383. return count;
  384. }
  385. int ff_mov_add_hinted_packet(AVFormatContext *s, AVPacket *pkt,
  386. int track_index, int sample)
  387. {
  388. MOVMuxContext *mov = s->priv_data;
  389. MOVTrack *trk = &mov->tracks[track_index];
  390. AVFormatContext *rtp_ctx = trk->rtp_ctx;
  391. uint8_t *buf = NULL;
  392. int size;
  393. ByteIOContext *hintbuf = NULL;
  394. AVPacket hint_pkt;
  395. int ret = 0, count;
  396. if (!rtp_ctx)
  397. return AVERROR(ENOENT);
  398. if (!rtp_ctx->pb)
  399. return AVERROR(ENOMEM);
  400. sample_queue_push(&trk->sample_queue, pkt, sample);
  401. /* Feed the packet to the RTP muxer */
  402. ff_write_chained(rtp_ctx, 0, pkt, s);
  403. /* Fetch the output from the RTP muxer, open a new output buffer
  404. * for next time. */
  405. size = url_close_dyn_buf(rtp_ctx->pb, &buf);
  406. if ((ret = url_open_dyn_packet_buf(&rtp_ctx->pb,
  407. RTP_MAX_PACKET_SIZE)) < 0)
  408. goto done;
  409. if (size <= 0)
  410. goto done;
  411. /* Open a buffer for writing the hint */
  412. if ((ret = url_open_dyn_buf(&hintbuf)) < 0)
  413. goto done;
  414. av_init_packet(&hint_pkt);
  415. count = write_hint_packets(hintbuf, buf, size, trk, &hint_pkt.dts);
  416. av_freep(&buf);
  417. /* Write the hint data into the hint track */
  418. hint_pkt.size = size = url_close_dyn_buf(hintbuf, &buf);
  419. hint_pkt.data = buf;
  420. hint_pkt.pts = hint_pkt.dts;
  421. hint_pkt.stream_index = track_index;
  422. if (pkt->flags & AV_PKT_FLAG_KEY)
  423. hint_pkt.flags |= AV_PKT_FLAG_KEY;
  424. if (count > 0)
  425. ff_mov_write_packet(s, &hint_pkt);
  426. done:
  427. av_free(buf);
  428. sample_queue_retain(&trk->sample_queue);
  429. return ret;
  430. }
  431. void ff_mov_close_hinting(MOVTrack *track) {
  432. AVFormatContext* rtp_ctx = track->rtp_ctx;
  433. uint8_t *ptr;
  434. av_freep(&track->enc);
  435. sample_queue_free(&track->sample_queue);
  436. if (!rtp_ctx)
  437. return;
  438. if (rtp_ctx->pb) {
  439. av_write_trailer(rtp_ctx);
  440. url_close_dyn_buf(rtp_ctx->pb, &ptr);
  441. av_free(ptr);
  442. }
  443. av_metadata_free(&rtp_ctx->streams[0]->metadata);
  444. av_metadata_free(&rtp_ctx->metadata);
  445. av_free(rtp_ctx->streams[0]);
  446. av_freep(&rtp_ctx);
  447. }