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.

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